migrate.go 1.87 KB
Newer Older
Łukasz Magiera's avatar
Łukasz Magiera committed
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
package fs

import (
	"io/ioutil"
	"os"
	"path/filepath"

	dcopy "github.com/otiai10/copy"
	"golang.org/x/xerrors"
)

func (f *FS) MigrateTo(to *FS, ssize uint64, symlink bool) error {
	for path := range f.paths {
		for _, dataType := range types {
			sectors, err := f.List(path, dataType)
			if err != nil {
				return err
			}

			for _, sector := range sectors {
				if err := f.migrateSector(to, ssize, sector, symlink); err != nil {
					return err
				}
			}
		}
	}
	return nil
}

func (f *FS) migrateSector(to *FS, ssize uint64, sector SectorPath, symlink bool) error {
	id, err := sector.id()
	if err != nil {
		return err
	}

	m, err := sector.miner()
	if err != nil {
		return err
	}

	newp, err := to.AllocSector(sector.typ(), m, ssize, false, id)
	if err != nil {
		return err
	}

	inf, err := os.Stat(string(sector))
	if err != nil {
		return err
	}

	if inf.IsDir() {
		return migrateDir(string(sector), string(newp), symlink)
	}
	return migrateFile(string(sector), string(newp), symlink)
}

func migrateDir(from, to string, symlink bool) error {
	tost, err := os.Stat(to)
	if err != nil {
		if !os.IsNotExist(err) {
			return err
		}

		if err := os.MkdirAll(to, 0755); err != nil {
			return err
		}
	} else if !tost.IsDir() {
		return xerrors.Errorf("target %q already exists and is a file (expected directory)")
	}

	dirents, err := ioutil.ReadDir(from)
	if err != nil {
		return err
	}

	for _, inf := range dirents {
		n := inf.Name()
		if inf.IsDir() {
			if err := migrateDir(filepath.Join(from, n), filepath.Join(to, n), symlink); err != nil {
				return err
			}
		} else {
			if err := migrateFile(filepath.Join(from, n), filepath.Join(to, n), symlink); err != nil {
				return err
			}
		}
	}

	return nil
}

func migrateFile(from, to string, symlink bool) error {
	if symlink {
		return os.Symlink(from, to)
	}

Łukasz Magiera's avatar
Łukasz Magiera committed
97
	log.Infof("copy %s -> %s", from, to)
Łukasz Magiera's avatar
Łukasz Magiera committed
98

Łukasz Magiera's avatar
Łukasz Magiera committed
99
100
	return dcopy.Copy(from, to)
}