summaryrefslogtreecommitdiffhomepage
path: root/paths/migrate.go
blob: 22f947611f4cd66089560e34afff42e2e496938a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause

package paths

import (
	"os"
	"path/filepath"

	"tailscale.com/types/logger"
)

// TryConfigFileMigration carefully copies the contents of oldFile to
// newFile, returning the path which should be used to read the config.
//   - if newFile already exists, don't modify it just return its path
//   - if neither oldFile nor newFile exist, return newFile for a fresh
//     default config to be written to.
//   - if oldFile exists but copying to newFile fails, return oldFile so
//     there will at least be some config to work with.
func TryConfigFileMigration(logf logger.Logf, oldFile, newFile string) string {
	_, err := os.Stat(newFile)
	if err == nil {
		// Common case for a system which has already been migrated.
		return newFile
	}
	if !os.IsNotExist(err) {
		logf("TryConfigFileMigration failed; new file: %v", err)
		return newFile
	}

	contents, err := os.ReadFile(oldFile)
	if err != nil {
		// Common case for a new user.
		return newFile
	}

	if err = MkStateDir(filepath.Dir(newFile)); err != nil {
		logf("TryConfigFileMigration failed; MkStateDir: %v", err)
		return oldFile
	}

	err = os.WriteFile(newFile, contents, 0600)
	if err != nil {
		removeErr := os.Remove(newFile)
		if removeErr != nil {
			logf("TryConfigFileMigration failed; write newFile no cleanup: %v, remove err: %v",
				err, removeErr)
			return oldFile
		}
		logf("TryConfigFileMigration failed; write newFile: %v", err)
		return oldFile
	}

	logf("TryConfigFileMigration: successfully migrated: from %v to %v",
		oldFile, newFile)

	return newFile
}