osutil.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  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. "sync"
  17. )
  18. var ErrNoHome = errors.New("No home directory found - set $HOME (or the platform equivalent).")
  19. // Try to keep this entire operation atomic-like. We shouldn't be doing this
  20. // often enough that there is any contention on this lock.
  21. var renameLock sync.Mutex
  22. // TryRename renames a file, leaving source file intact in case of failure.
  23. // Tries hard to succeed on various systems by temporarily tweaking directory
  24. // permissions and removing the destination file when necessary.
  25. func TryRename(from, to string) error {
  26. renameLock.Lock()
  27. defer renameLock.Unlock()
  28. return withPreparedTarget(to, func() error {
  29. return os.Rename(from, to)
  30. })
  31. }
  32. // Rename moves a temporary file to it's final place.
  33. // Will make sure to delete the from file if the operation fails, so use only
  34. // for situations like committing a temp file to it's final location.
  35. // Tries hard to succeed on various systems by temporarily tweaking directory
  36. // permissions and removing the destination file when necessary.
  37. func Rename(from, to string) error {
  38. // Don't leave a dangling temp file in case of rename error
  39. defer os.Remove(from)
  40. return TryRename(from, to)
  41. }
  42. // Copy copies the file content from source to destination.
  43. // Tries hard to succeed on various systems by temporarily tweaking directory
  44. // permissions and removing the destination file when necessary.
  45. func Copy(from, to string) (err error) {
  46. return withPreparedTarget(to, func() error {
  47. return copyFileContents(from, to)
  48. })
  49. }
  50. // InWritableDir calls fn(path), while making sure that the directory
  51. // containing `path` is writable for the duration of the call.
  52. func InWritableDir(fn func(string) error, path string) error {
  53. dir := filepath.Dir(path)
  54. info, err := os.Stat(dir)
  55. if err != nil {
  56. return err
  57. }
  58. if !info.IsDir() {
  59. return errors.New("Not a directory: " + path)
  60. }
  61. if info.Mode()&0200 == 0 {
  62. // A non-writeable directory (for this user; we assume that's the
  63. // relevant part). Temporarily change the mode so we can delete the
  64. // file or directory inside it.
  65. err = os.Chmod(dir, 0755)
  66. if err == nil {
  67. defer func() {
  68. err = os.Chmod(dir, info.Mode())
  69. if err != nil {
  70. // We managed to change the permission bits like a
  71. // millisecond ago, so it'd be bizarre if we couldn't
  72. // change it back.
  73. panic(err)
  74. }
  75. }()
  76. }
  77. }
  78. return fn(path)
  79. }
  80. // On Windows, removes the read-only attribute from the target prior deletion.
  81. func Remove(path string) error {
  82. if runtime.GOOS == "windows" {
  83. info, err := os.Stat(path)
  84. if err != nil {
  85. return err
  86. }
  87. if info.Mode()&0200 == 0 {
  88. os.Chmod(path, 0700)
  89. }
  90. }
  91. return os.Remove(path)
  92. }
  93. func ExpandTilde(path string) (string, error) {
  94. if path == "~" {
  95. return getHomeDir()
  96. }
  97. path = filepath.FromSlash(path)
  98. if !strings.HasPrefix(path, fmt.Sprintf("~%c", os.PathSeparator)) {
  99. return path, nil
  100. }
  101. home, err := getHomeDir()
  102. if err != nil {
  103. return "", err
  104. }
  105. return filepath.Join(home, path[2:]), nil
  106. }
  107. func getHomeDir() (string, error) {
  108. var home string
  109. switch runtime.GOOS {
  110. case "windows":
  111. home = filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  112. if home == "" {
  113. home = os.Getenv("UserProfile")
  114. }
  115. default:
  116. home = os.Getenv("HOME")
  117. }
  118. if home == "" {
  119. return "", ErrNoHome
  120. }
  121. return home, nil
  122. }
  123. // Tries hard to succeed on various systems by temporarily tweaking directory
  124. // permissions and removing the destination file when necessary.
  125. func withPreparedTarget(to string, f func() error) error {
  126. // Make sure the destination directory is writeable
  127. toDir := filepath.Dir(to)
  128. if info, err := os.Stat(toDir); err == nil && info.IsDir() && info.Mode()&0200 == 0 {
  129. os.Chmod(toDir, 0755)
  130. defer os.Chmod(toDir, info.Mode())
  131. }
  132. // On Windows, make sure the destination file is writeable (or we can't delete it)
  133. if runtime.GOOS == "windows" {
  134. os.Chmod(to, 0666)
  135. err := os.Remove(to)
  136. if err != nil && !os.IsNotExist(err) {
  137. return err
  138. }
  139. }
  140. return f()
  141. }
  142. // copyFileContents copies the contents of the file named src to the file named
  143. // by dst. The file will be created if it does not already exist. If the
  144. // destination file exists, all it's contents will be replaced by the contents
  145. // of the source file.
  146. func copyFileContents(src, dst string) (err error) {
  147. in, err := os.Open(src)
  148. if err != nil {
  149. return
  150. }
  151. defer in.Close()
  152. out, err := os.Create(dst)
  153. if err != nil {
  154. return
  155. }
  156. defer func() {
  157. cerr := out.Close()
  158. if err == nil {
  159. err = cerr
  160. }
  161. }()
  162. if _, err = io.Copy(out, in); err != nil {
  163. return
  164. }
  165. err = out.Sync()
  166. return
  167. }