osutil.go 5.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. // Copyright (C) 2014 The Syncthing Authors.
  2. //
  3. // This program is free software: you can redistribute it and/or modify it
  4. // under the terms of the GNU General Public License as published by the Free
  5. // Software Foundation, either version 3 of the License, or (at your option)
  6. // any later version.
  7. //
  8. // This program is distributed in the hope that it will be useful, but WITHOUT
  9. // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
  10. // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for
  11. // more details.
  12. //
  13. // You should have received a copy of the GNU General Public License along
  14. // with this program. If not, see <http://www.gnu.org/licenses/>.
  15. // Package osutil implements utilities for native OS support.
  16. package osutil
  17. import (
  18. "errors"
  19. "fmt"
  20. "io"
  21. "os"
  22. "path/filepath"
  23. "runtime"
  24. "strings"
  25. "sync"
  26. )
  27. var ErrNoHome = errors.New("No home directory found - set $HOME (or the platform equivalent).")
  28. // Try to keep this entire operation atomic-like. We shouldn't be doing this
  29. // often enough that there is any contention on this lock.
  30. var renameLock sync.Mutex
  31. // TryRename renames a file, leaving source file intact in case of failure.
  32. // Tries hard to succeed on various systems by temporarily tweaking directory
  33. // permissions and removing the destination file when necessary.
  34. func TryRename(from, to string) error {
  35. renameLock.Lock()
  36. defer renameLock.Unlock()
  37. return withPreparedTarget(to, func() error {
  38. return os.Rename(from, to)
  39. })
  40. }
  41. // Rename moves a temporary file to it's final place.
  42. // Will make sure to delete the from file if the operation fails, so use only
  43. // for situations like committing a temp file to it's final location.
  44. // Tries hard to succeed on various systems by temporarily tweaking directory
  45. // permissions and removing the destination file when necessary.
  46. func Rename(from, to string) error {
  47. // Don't leave a dangling temp file in case of rename error
  48. defer os.Remove(from)
  49. return TryRename(from, to)
  50. }
  51. // Copy copies the file content from source to destination.
  52. // Tries hard to succeed on various systems by temporarily tweaking directory
  53. // permissions and removing the destination file when necessary.
  54. func Copy(from, to string) (err error) {
  55. return withPreparedTarget(to, func() error {
  56. return copyFileContents(from, to)
  57. })
  58. }
  59. // InWritableDir calls fn(path), while making sure that the directory
  60. // containing `path` is writable for the duration of the call.
  61. func InWritableDir(fn func(string) error, path string) error {
  62. dir := filepath.Dir(path)
  63. info, err := os.Stat(dir)
  64. if err != nil {
  65. return err
  66. }
  67. if !info.IsDir() {
  68. return errors.New("Not a directory: " + path)
  69. }
  70. if info.Mode()&0200 == 0 {
  71. // A non-writeable directory (for this user; we assume that's the
  72. // relevant part). Temporarily change the mode so we can delete the
  73. // file or directory inside it.
  74. err = os.Chmod(dir, 0755)
  75. if err == nil {
  76. defer func() {
  77. err = os.Chmod(dir, info.Mode())
  78. if err != nil {
  79. // We managed to change the permission bits like a
  80. // millisecond ago, so it'd be bizarre if we couldn't
  81. // change it back.
  82. panic(err)
  83. }
  84. }()
  85. }
  86. }
  87. return fn(path)
  88. }
  89. func ExpandTilde(path string) (string, error) {
  90. if path == "~" {
  91. return getHomeDir()
  92. }
  93. path = filepath.FromSlash(path)
  94. if !strings.HasPrefix(path, fmt.Sprintf("~%c", os.PathSeparator)) {
  95. return path, nil
  96. }
  97. home, err := getHomeDir()
  98. if err != nil {
  99. return "", err
  100. }
  101. return filepath.Join(home, path[2:]), nil
  102. }
  103. func getHomeDir() (string, error) {
  104. var home string
  105. switch runtime.GOOS {
  106. case "windows":
  107. home = filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  108. if home == "" {
  109. home = os.Getenv("UserProfile")
  110. }
  111. default:
  112. home = os.Getenv("HOME")
  113. }
  114. if home == "" {
  115. return "", ErrNoHome
  116. }
  117. return home, nil
  118. }
  119. // Tries hard to succeed on various systems by temporarily tweaking directory
  120. // permissions and removing the destination file when necessary.
  121. func withPreparedTarget(to string, f func() error) error {
  122. // Make sure the destination directory is writeable
  123. toDir := filepath.Dir(to)
  124. if info, err := os.Stat(toDir); err == nil && info.IsDir() && info.Mode()&0200 == 0 {
  125. os.Chmod(toDir, 0755)
  126. defer os.Chmod(toDir, info.Mode())
  127. }
  128. // On Windows, make sure the destination file is writeable (or we can't delete it)
  129. if runtime.GOOS == "windows" {
  130. os.Chmod(to, 0666)
  131. err := os.Remove(to)
  132. if err != nil && !os.IsNotExist(err) {
  133. return err
  134. }
  135. }
  136. return f()
  137. }
  138. // copyFileContents copies the contents of the file named src to the file named
  139. // by dst. The file will be created if it does not already exist. If the
  140. // destination file exists, all it's contents will be replaced by the contents
  141. // of the source file.
  142. func copyFileContents(src, dst string) (err error) {
  143. in, err := os.Open(src)
  144. if err != nil {
  145. return
  146. }
  147. defer in.Close()
  148. out, err := os.Create(dst)
  149. if err != nil {
  150. return
  151. }
  152. defer func() {
  153. cerr := out.Close()
  154. if err == nil {
  155. err = cerr
  156. }
  157. }()
  158. if _, err = io.Copy(out, in); err != nil {
  159. return
  160. }
  161. err = out.Sync()
  162. return
  163. }