osutil.go 895 B

12345678910111213141516171819202122232425262728293031323334
  1. // Copyright (C) 2014 Jakob Borg and Contributors (see the CONTRIBUTORS file).
  2. // All rights reserved. Use of this source code is governed by an MIT-style
  3. // license that can be found in the LICENSE file.
  4. // Package osutil implements utilities for native OS support.
  5. package osutil
  6. import (
  7. "os"
  8. "path/filepath"
  9. "runtime"
  10. )
  11. func Rename(from, to string) error {
  12. // Make sure the destination directory is writeable
  13. toDir := filepath.Dir(to)
  14. if info, err := os.Stat(toDir); err == nil {
  15. os.Chmod(toDir, 0777)
  16. defer os.Chmod(toDir, info.Mode())
  17. }
  18. // On Windows, make sure the destination file is writeable (or we can't delete it)
  19. if runtime.GOOS == "windows" {
  20. os.Chmod(to, 0666)
  21. err := os.Remove(to)
  22. if err != nil && !os.IsNotExist(err) {
  23. return err
  24. }
  25. }
  26. // Don't leave a dangling temp file in case of rename error
  27. defer os.Remove(from)
  28. return os.Rename(from, to)
  29. }