osutil.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. 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. // IsSymlink returns true if given path is a symbolic link.
  32. func IsSymlink(path string) bool {
  33. if !IsExist(path) {
  34. return false
  35. }
  36. fileInfo, err := os.Lstat(path)
  37. if err != nil {
  38. return false
  39. }
  40. return fileInfo.Mode()&os.ModeSymlink != 0
  41. }
  42. // CurrentUsername returns the username of the current user.
  43. func CurrentUsername() string {
  44. username := os.Getenv("USER")
  45. if len(username) > 0 {
  46. return username
  47. }
  48. username = os.Getenv("USERNAME")
  49. if len(username) > 0 {
  50. return username
  51. }
  52. if user, err := user.Current(); err == nil {
  53. username = user.Username
  54. }
  55. return username
  56. }