osutil.go 5.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. // Package osutil implements utilities for native OS support.
  7. package osutil
  8. import (
  9. "errors"
  10. "fmt"
  11. "io"
  12. "os"
  13. "path/filepath"
  14. "runtime"
  15. "strings"
  16. "github.com/calmh/du"
  17. "github.com/syncthing/syncthing/lib/sync"
  18. )
  19. var ErrNoHome = errors.New("No home directory found - set $HOME (or the platform equivalent).")
  20. // Try to keep this entire operation atomic-like. We shouldn't be doing this
  21. // often enough that there is any contention on this lock.
  22. var renameLock = sync.NewMutex()
  23. // TryRename renames a file, leaving source file intact in case of failure.
  24. // Tries hard to succeed on various systems by temporarily tweaking directory
  25. // permissions and removing the destination file when necessary.
  26. func TryRename(from, to string) error {
  27. renameLock.Lock()
  28. defer renameLock.Unlock()
  29. return withPreparedTarget(from, to, func() error {
  30. return os.Rename(from, to)
  31. })
  32. }
  33. // Rename moves a temporary file to it's final place.
  34. // Will make sure to delete the from file if the operation fails, so use only
  35. // for situations like committing a temp file to it's final location.
  36. // Tries hard to succeed on various systems by temporarily tweaking directory
  37. // permissions and removing the destination file when necessary.
  38. func Rename(from, to string) error {
  39. // Don't leave a dangling temp file in case of rename error
  40. if !(runtime.GOOS == "windows" && strings.EqualFold(from, to)) {
  41. defer os.Remove(from)
  42. }
  43. return TryRename(from, to)
  44. }
  45. // Copy copies the file content from source to destination.
  46. // Tries hard to succeed on various systems by temporarily tweaking directory
  47. // permissions and removing the destination file when necessary.
  48. func Copy(from, to string) (err error) {
  49. return withPreparedTarget(from, to, func() error {
  50. return copyFileContents(from, to)
  51. })
  52. }
  53. // InWritableDir calls fn(path), while making sure that the directory
  54. // containing `path` is writable for the duration of the call.
  55. func InWritableDir(fn func(string) error, path string) error {
  56. dir := filepath.Dir(path)
  57. info, err := os.Stat(dir)
  58. if err != nil {
  59. return err
  60. }
  61. if !info.IsDir() {
  62. return errors.New("Not a directory: " + path)
  63. }
  64. if info.Mode()&0200 == 0 {
  65. // A non-writeable directory (for this user; we assume that's the
  66. // relevant part). Temporarily change the mode so we can delete the
  67. // file or directory inside it.
  68. err = os.Chmod(dir, 0755)
  69. if err == nil {
  70. defer func() {
  71. err = os.Chmod(dir, info.Mode())
  72. if err != nil {
  73. // We managed to change the permission bits like a
  74. // millisecond ago, so it'd be bizarre if we couldn't
  75. // change it back.
  76. panic(err)
  77. }
  78. }()
  79. }
  80. }
  81. return fn(path)
  82. }
  83. func ExpandTilde(path string) (string, error) {
  84. if path == "~" {
  85. return getHomeDir()
  86. }
  87. path = filepath.FromSlash(path)
  88. if !strings.HasPrefix(path, fmt.Sprintf("~%c", os.PathSeparator)) {
  89. return path, nil
  90. }
  91. home, err := getHomeDir()
  92. if err != nil {
  93. return "", err
  94. }
  95. return filepath.Join(home, path[2:]), nil
  96. }
  97. func getHomeDir() (string, error) {
  98. var home string
  99. switch runtime.GOOS {
  100. case "windows":
  101. home = filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  102. if home == "" {
  103. home = os.Getenv("UserProfile")
  104. }
  105. default:
  106. home = os.Getenv("HOME")
  107. }
  108. if home == "" {
  109. return "", ErrNoHome
  110. }
  111. return home, nil
  112. }
  113. // Tries hard to succeed on various systems by temporarily tweaking directory
  114. // permissions and removing the destination file when necessary.
  115. func withPreparedTarget(from, to string, f func() error) error {
  116. // Make sure the destination directory is writeable
  117. toDir := filepath.Dir(to)
  118. if info, err := os.Stat(toDir); err == nil && info.IsDir() && info.Mode()&0200 == 0 {
  119. os.Chmod(toDir, 0755)
  120. defer os.Chmod(toDir, info.Mode())
  121. }
  122. // On Windows, make sure the destination file is writeable (or we can't delete it)
  123. if runtime.GOOS == "windows" {
  124. os.Chmod(to, 0666)
  125. if !strings.EqualFold(from, to) {
  126. err := os.Remove(to)
  127. if err != nil && !os.IsNotExist(err) {
  128. return err
  129. }
  130. }
  131. }
  132. return f()
  133. }
  134. // copyFileContents copies the contents of the file named src to the file named
  135. // by dst. The file will be created if it does not already exist. If the
  136. // destination file exists, all it's contents will be replaced by the contents
  137. // of the source file.
  138. func copyFileContents(src, dst string) (err error) {
  139. in, err := os.Open(src)
  140. if err != nil {
  141. return
  142. }
  143. defer in.Close()
  144. out, err := os.Create(dst)
  145. if err != nil {
  146. return
  147. }
  148. defer func() {
  149. cerr := out.Close()
  150. if err == nil {
  151. err = cerr
  152. }
  153. }()
  154. _, err = io.Copy(out, in)
  155. return
  156. }
  157. var execExts map[string]bool
  158. func init() {
  159. // PATHEXT contains a list of executable file extensions, on Windows
  160. pathext := filepath.SplitList(os.Getenv("PATHEXT"))
  161. // We want the extensions in execExts to be lower case
  162. execExts = make(map[string]bool, len(pathext))
  163. for _, ext := range pathext {
  164. execExts[strings.ToLower(ext)] = true
  165. }
  166. }
  167. // IsWindowsExecutable returns true if the given path has an extension that is
  168. // in the list of executable extensions.
  169. func IsWindowsExecutable(path string) bool {
  170. return execExts[strings.ToLower(filepath.Ext(path))]
  171. }
  172. func DiskFreeBytes(path string) (free int64, err error) {
  173. u, err := du.Get(path)
  174. return u.FreeBytes, err
  175. }
  176. func DiskFreePercentage(path string) (freePct float64, err error) {
  177. u, err := du.Get(path)
  178. return (float64(u.FreeBytes) / float64(u.TotalBytes)) * 100, err
  179. }