osutil.go 4.6 KB

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