osutil.go 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223
  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. // Remove removes the given path. On Windows, removes the read-only attribute
  84. // from the target prior to deletion.
  85. func Remove(path string) error {
  86. if runtime.GOOS == "windows" {
  87. info, err := os.Stat(path)
  88. if err != nil {
  89. return err
  90. }
  91. if info.Mode()&0200 == 0 {
  92. os.Chmod(path, 0700)
  93. }
  94. }
  95. return os.Remove(path)
  96. }
  97. func ExpandTilde(path string) (string, error) {
  98. if path == "~" {
  99. return getHomeDir()
  100. }
  101. path = filepath.FromSlash(path)
  102. if !strings.HasPrefix(path, fmt.Sprintf("~%c", os.PathSeparator)) {
  103. return path, nil
  104. }
  105. home, err := getHomeDir()
  106. if err != nil {
  107. return "", err
  108. }
  109. return filepath.Join(home, path[2:]), nil
  110. }
  111. func getHomeDir() (string, error) {
  112. var home string
  113. switch runtime.GOOS {
  114. case "windows":
  115. home = filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  116. if home == "" {
  117. home = os.Getenv("UserProfile")
  118. }
  119. default:
  120. home = os.Getenv("HOME")
  121. }
  122. if home == "" {
  123. return "", ErrNoHome
  124. }
  125. return home, nil
  126. }
  127. // Tries hard to succeed on various systems by temporarily tweaking directory
  128. // permissions and removing the destination file when necessary.
  129. func withPreparedTarget(from, to string, f func() error) error {
  130. // Make sure the destination directory is writeable
  131. toDir := filepath.Dir(to)
  132. if info, err := os.Stat(toDir); err == nil && info.IsDir() && info.Mode()&0200 == 0 {
  133. os.Chmod(toDir, 0755)
  134. defer os.Chmod(toDir, info.Mode())
  135. }
  136. // On Windows, make sure the destination file is writeable (or we can't delete it)
  137. if runtime.GOOS == "windows" {
  138. os.Chmod(to, 0666)
  139. if !strings.EqualFold(from, to) {
  140. err := os.Remove(to)
  141. if err != nil && !os.IsNotExist(err) {
  142. return err
  143. }
  144. }
  145. }
  146. return f()
  147. }
  148. // copyFileContents copies the contents of the file named src to the file named
  149. // by dst. The file will be created if it does not already exist. If the
  150. // destination file exists, all it's contents will be replaced by the contents
  151. // of the source file.
  152. func copyFileContents(src, dst string) (err error) {
  153. in, err := os.Open(src)
  154. if err != nil {
  155. return
  156. }
  157. defer in.Close()
  158. out, err := os.Create(dst)
  159. if err != nil {
  160. return
  161. }
  162. defer func() {
  163. cerr := out.Close()
  164. if err == nil {
  165. err = cerr
  166. }
  167. }()
  168. if _, err = io.Copy(out, in); err != nil {
  169. return
  170. }
  171. err = out.Sync()
  172. return
  173. }
  174. var execExts map[string]bool
  175. func init() {
  176. // PATHEXT contains a list of executable file extensions, on Windows
  177. pathext := filepath.SplitList(os.Getenv("PATHEXT"))
  178. // We want the extensions in execExts to be lower case
  179. execExts = make(map[string]bool, len(pathext))
  180. for _, ext := range pathext {
  181. execExts[strings.ToLower(ext)] = true
  182. }
  183. }
  184. // IsWindowsExecutable returns true if the given path has an extension that is
  185. // in the list of executable extensions.
  186. func IsWindowsExecutable(path string) bool {
  187. return execExts[strings.ToLower(filepath.Ext(path))]
  188. }
  189. func DiskFreeBytes(path string) (free int64, err error) {
  190. u, err := du.Get(path)
  191. return u.FreeBytes, err
  192. }
  193. func DiskFreePercentage(path string) (freePct float64, err error) {
  194. u, err := du.Get(path)
  195. return (float64(u.FreeBytes) / float64(u.TotalBytes)) * 100, err
  196. }