undo the processed renames on error

This commit is contained in:
itchyny 2020-01-09 13:04:18 +09:00
parent 2a878af8f0
commit 0ed17e263c
2 changed files with 33 additions and 1 deletions

10
mmv.go
View file

@ -13,8 +13,16 @@ func Rename(files map[string]string) error {
if err != nil {
return err
}
for _, r := range rs {
for i, r := range rs {
if err := doRename(r.src, r.dst); err != nil {
// undo on error not to leave the temporary files
// this does not undo directory creation
for i--; i >= 0; i-- {
if r = rs[i]; os.Rename(r.dst, r.src) != nil {
// something wrong happens so give up not to overwrite files
break
}
}
return err
}
}

View file

@ -254,6 +254,30 @@ func TestRename(t *testing.T) {
},
err: "duplicate destination: foo",
},
{
name: "undo on error",
files: map[string]string{
"foo": "bar",
"bar": "foo",
"baz": "qux",
"qux": "quux",
"quux": "baz",
},
count: 7,
contents: map[string]string{
"foo": "0",
"bar": "1",
"baz": "2",
"qux": "3",
},
expected: map[string]string{
"foo": "0",
"bar": "1",
"baz": "2",
"qux": "3",
},
err: "quux: ", // no such file or directory
},
{
name: "create destination directory",
files: map[string]string{