migrate.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package paths
  4. import (
  5. "os"
  6. "path/filepath"
  7. "tailscale.com/types/logger"
  8. )
  9. // TryConfigFileMigration carefully copies the contents of oldFile to
  10. // newFile, returning the path which should be used to read the config.
  11. // - if newFile already exists, don't modify it just return its path
  12. // - if neither oldFile nor newFile exist, return newFile for a fresh
  13. // default config to be written to.
  14. // - if oldFile exists but copying to newFile fails, return oldFile so
  15. // there will at least be some config to work with.
  16. func TryConfigFileMigration(logf logger.Logf, oldFile, newFile string) string {
  17. _, err := os.Stat(newFile)
  18. if err == nil {
  19. // Common case for a system which has already been migrated.
  20. return newFile
  21. }
  22. if !os.IsNotExist(err) {
  23. logf("TryConfigFileMigration failed; new file: %v", err)
  24. return newFile
  25. }
  26. contents, err := os.ReadFile(oldFile)
  27. if err != nil {
  28. // Common case for a new user.
  29. return newFile
  30. }
  31. if err = MkStateDir(filepath.Dir(newFile)); err != nil {
  32. logf("TryConfigFileMigration failed; MkStateDir: %v", err)
  33. return oldFile
  34. }
  35. err = os.WriteFile(newFile, contents, 0600)
  36. if err != nil {
  37. removeErr := os.Remove(newFile)
  38. if removeErr != nil {
  39. logf("TryConfigFileMigration failed; write newFile no cleanup: %v, remove err: %v",
  40. err, removeErr)
  41. return oldFile
  42. }
  43. logf("TryConfigFileMigration failed; write newFile: %v", err)
  44. return oldFile
  45. }
  46. logf("TryConfigFileMigration: successfully migrated: from %v to %v",
  47. oldFile, newFile)
  48. return newFile
  49. }