osutil.go 4.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  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. if info, err := os.Stat(dir); err == nil && info.IsDir() && info.Mode()&0200 == 0 {
  64. // A non-writeable directory (for this user; we assume that's the
  65. // relevant part). Temporarily change the mode so we can delete the
  66. // file or directory inside it.
  67. err = os.Chmod(dir, 0755)
  68. if err == nil {
  69. defer func() {
  70. err = os.Chmod(dir, info.Mode())
  71. if err != nil {
  72. // We managed to change the permission bits like a
  73. // millisecond ago, so it'd be bizarre if we couldn't
  74. // change it back.
  75. panic(err)
  76. }
  77. }()
  78. }
  79. }
  80. return fn(path)
  81. }
  82. func ExpandTilde(path string) (string, error) {
  83. if path == "~" {
  84. return getHomeDir()
  85. }
  86. path = filepath.FromSlash(path)
  87. if !strings.HasPrefix(path, fmt.Sprintf("~%c", os.PathSeparator)) {
  88. return path, nil
  89. }
  90. home, err := getHomeDir()
  91. if err != nil {
  92. return "", err
  93. }
  94. return filepath.Join(home, path[2:]), nil
  95. }
  96. func getHomeDir() (string, error) {
  97. var home string
  98. switch runtime.GOOS {
  99. case "windows":
  100. home = filepath.Join(os.Getenv("HomeDrive"), os.Getenv("HomePath"))
  101. if home == "" {
  102. home = os.Getenv("UserProfile")
  103. }
  104. default:
  105. home = os.Getenv("HOME")
  106. }
  107. if home == "" {
  108. return "", ErrNoHome
  109. }
  110. return home, nil
  111. }
  112. // Tries hard to succeed on various systems by temporarily tweaking directory
  113. // permissions and removing the destination file when necessary.
  114. func withPreparedTarget(to string, f func() error) error {
  115. // Make sure the destination directory is writeable
  116. toDir := filepath.Dir(to)
  117. if info, err := os.Stat(toDir); err == nil && info.IsDir() && info.Mode()&0200 == 0 {
  118. os.Chmod(toDir, 0755)
  119. defer os.Chmod(toDir, info.Mode())
  120. }
  121. // On Windows, make sure the destination file is writeable (or we can't delete it)
  122. if runtime.GOOS == "windows" {
  123. os.Chmod(to, 0666)
  124. err := os.Remove(to)
  125. if err != nil && !os.IsNotExist(err) {
  126. return err
  127. }
  128. }
  129. return f()
  130. }
  131. // copyFileContents copies the contents of the file named src to the file named
  132. // by dst. The file will be created if it does not already exist. If the
  133. // destination file exists, all it's contents will be replaced by the contents
  134. // of the source file.
  135. func copyFileContents(src, dst string) (err error) {
  136. in, err := os.Open(src)
  137. if err != nil {
  138. return
  139. }
  140. defer in.Close()
  141. out, err := os.Create(dst)
  142. if err != nil {
  143. return
  144. }
  145. defer func() {
  146. cerr := out.Close()
  147. if err == nil {
  148. err = cerr
  149. }
  150. }()
  151. if _, err = io.Copy(out, in); err != nil {
  152. return
  153. }
  154. err = out.Sync()
  155. return
  156. }