Skip to content

Commit 46ecb9d

Browse files
authored
Merge pull request #55 from ipfs/reversible
fs-repo-migrations can now revert
2 parents 4e8e0b4 + 8d28369 commit 46ecb9d

File tree

1 file changed

+27
-10
lines changed

1 file changed

+27
-10
lines changed

main.go

Lines changed: 27 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -65,8 +65,8 @@ func GetIpfsDir() (string, error) {
6565
return "", err
6666
}
6767

68-
func runMigration(n int) error {
69-
fmt.Printf("===> Running migration %d to %d...\n", n, n+1)
68+
func runMigration(from int, to int) error {
69+
fmt.Printf("===> Running migration %d to %d...\n", from, to)
7070
path, err := GetIpfsDir()
7171
if err != nil {
7272
return err
@@ -76,18 +76,29 @@ func runMigration(n int) error {
7676
opts.Path = path
7777
opts.Verbose = true
7878

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

8794
func doMigrate(from, to int) error {
88-
cur := from
89-
for ; cur < to; cur++ {
90-
err := runMigration(cur)
95+
step := 1
96+
if from > to {
97+
step = -1
98+
}
99+
100+
for cur := from; cur != to; cur += step {
101+
err := runMigration(cur, cur + step)
91102
if err != nil {
92103
return err
93104
}
@@ -133,6 +144,7 @@ func main() {
133144
target := flag.Int("to", CurrentVersion, "specify version to upgrade to")
134145
yes := flag.Bool("y", false, "answer yes to all prompts")
135146
version := flag.Bool("v", false, "print highest repo version and exit")
147+
revertOk := flag.Bool("revert-ok", false, "allow running migrations backward")
136148

137149
flag.Parse()
138150

@@ -158,8 +170,13 @@ func main() {
158170
os.Exit(1)
159171
}
160172

161-
if vnum >= *target {
162-
fmt.Println("ipfs migration: already at or above target version number")
173+
if vnum > *target && !*revertOk {
174+
fmt.Println("ipfs migration: attempt to run backward migration\nTo allow, run this command again with --revert-ok")
175+
os.Exit(1)
176+
}
177+
178+
if vnum == *target {
179+
fmt.Println("ipfs migration: already at target version number")
163180
return
164181
}
165182

0 commit comments

Comments
 (0)