Skip to content

Commit 433937b

Browse files
committed
fs-repo-migrations can now revert
1 parent b4c3be0 commit 433937b

File tree

1 file changed

+22
-10
lines changed

1 file changed

+22
-10
lines changed

main.go

Lines changed: 22 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -61,8 +61,8 @@ func GetIpfsDir() (string, error) {
6161
return "", err
6262
}
6363

64-
func runMigration(n int) error {
65-
fmt.Printf("===> Running migration %d to %d...\n", n, n+1)
64+
func runMigration(from int, to int, backward bool) error {
65+
fmt.Printf("===> Running migration %d to %d...\n", from, to)
6666
path, err := GetIpfsDir()
6767
if err != nil {
6868
return err
@@ -72,18 +72,30 @@ func runMigration(n int) error {
7272
opts.Path = path
7373
opts.Verbose = true
7474

75-
err = migrations[n].Apply(opts)
75+
if to > from {
76+
err = migrations[from].Apply(opts)
77+
} else if to < from {
78+
err = migrations[to].Revert(opts)
79+
} else {
80+
// catch this earlier. expected invariant violated.
81+
err = fmt.Errorf("attempt to run migration to same version")
82+
}
7683
if err != nil {
77-
return fmt.Errorf("migration %d to %d failed: %s", n, n+1, err)
84+
return fmt.Errorf("migration %d to %d failed: %s", from, to, err)
7885
}
79-
fmt.Printf("===> Migration %d to %d succeeded!\n", n, n+1)
86+
fmt.Printf("===> Migration %d to %d succeeded!\n", from, to)
8087
return nil
8188
}
8289

8390
func doMigrate(from, to int) error {
84-
cur := from
85-
for ; cur < to; cur++ {
86-
err := runMigration(cur)
91+
backward := from > to
92+
step := 1
93+
if backward {
94+
step = -1
95+
}
96+
97+
for cur := from; cur != to; cur += step {
98+
err := runMigration(cur, cur + step, backward)
8799
if err != nil {
88100
return err
89101
}
@@ -154,8 +166,8 @@ func main() {
154166
os.Exit(1)
155167
}
156168

157-
if vnum >= *target {
158-
fmt.Println("ipfs migration: already at or above target version number")
169+
if vnum == *target {
170+
fmt.Println("ipfs migration: already at target version number")
159171
return
160172
}
161173

0 commit comments

Comments
 (0)