return error on duplicate destination

This commit is contained in:
itchyny 2020-01-08 00:08:30 +09:00
parent 33d7af2229
commit 8d8905510f
2 changed files with 32 additions and 2 deletions

11
mmv.go
View file

@ -25,11 +25,22 @@ type rename struct {
src, dst string
}
type sameDestinationError struct {
path string
}
func (err *sameDestinationError) Error() string {
return fmt.Sprintf("duplicate destination: %s", err.path)
}
func buildRenames(files map[string]string) ([]rename, error) {
rs := make([]rename, 0, 2*len(files))
vs := make(map[string]int, len(files))
revs := make(map[string]string, len(files))
for src, dst := range files {
if _, ok := revs[dst]; ok {
return nil, &sameDestinationError{dst}
}
revs[dst] = src
}
var i int

View file

@ -132,6 +132,20 @@ func TestMove(t *testing.T) {
"foo": "2",
},
},
{
name: "same destination error",
files: map[string]string{
"foo": "baz",
"bar": "baz",
"baz": "qux",
},
contents: map[string]string{
"foo": "0",
"bar": "1",
"baz": "2",
},
err: &sameDestinationError{"baz"},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
@ -142,8 +156,13 @@ func TestMove(t *testing.T) {
require.NoError(t, setupFiles(tc.contents))
rs, _ := buildRenames(tc.files)
assert.Equal(t, tc.cnt, len(rs))
require.NoError(t, Move(tc.files))
assert.Equal(t, tc.expected, fileContents("."))
got := Move(tc.files)
if tc.err == nil {
require.NoError(t, got)
assert.Equal(t, tc.expected, fileContents("."))
} else {
assert.Equal(t, tc.err, got)
}
})
}
}