From 8d8905510fb61f0a482f2291a895c76fd6c59cc6 Mon Sep 17 00:00:00 2001 From: itchyny Date: Wed, 8 Jan 2020 00:08:30 +0900 Subject: [PATCH] return error on duplicate destination --- mmv.go | 11 +++++++++++ mmv_test.go | 23 +++++++++++++++++++++-- 2 files changed, 32 insertions(+), 2 deletions(-) diff --git a/mmv.go b/mmv.go index 58f2ab4..bd1da4e 100644 --- a/mmv.go +++ b/mmv.go @@ -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 diff --git a/mmv_test.go b/mmv_test.go index 1128996..761976c 100644 --- a/mmv_test.go +++ b/mmv_test.go @@ -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) + } }) } }