From 1bb8c867610d1a19352bae723687a4df21a59c24 Mon Sep 17 00:00:00 2001 From: itchyny Date: Wed, 8 Jan 2020 10:27:20 +0900 Subject: [PATCH] add comments to the main logic --- mmv.go | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/mmv.go b/mmv.go index ea0f3e6..4f12baf 100644 --- a/mmv.go +++ b/mmv.go @@ -40,12 +40,15 @@ func (err *sameDestinationError) Error() string { } func buildRenames(files map[string]string) ([]rename, error) { - rs := make([]rename, 0, 2*len(files)) - revs := make(map[string]string, len(files)) + revs := make(map[string]string, len(files)) // reverse of files + + // list the current rename sources srcs := make([]string, 0, len(files)) for src := range files { srcs = append(srcs, src) } + + // clean the paths and check duplication for _, src := range srcs { dst := files[src] if src == "" || dst == "" { @@ -65,19 +68,26 @@ func buildRenames(files map[string]string) ([]rename, error) { } revs[dst] = src } + + // remove source == destination for src, dst := range files { if src == dst { delete(files, src) delete(revs, dst) } } + + // list the renames var i int + rs := make([]rename, 0, 2*len(files)) vs := make(map[string]int, len(files)) for _, dst := range files { if vs[dst] > 0 { continue } - i++ + i++ // connected component identifier + + // mark the nodes in the connected component and check cycle var cycle bool for { vs[dst] = i @@ -91,12 +101,16 @@ func buildRenames(files map[string]string) ([]rename, error) { break } } + + // if there is a cycle, rename to a temporary file var tmp string if cycle { tmp = randomPath(filepath.Dir(dst)) rs = append(rs, rename{dst, tmp}) vs[dst]-- } + + // rename from the leaf node for { if src, ok := revs[dst]; ok && (!cycle || vs[src] == i) { rs = append(rs, rename{src, dst}) @@ -108,6 +122,8 @@ func buildRenames(files map[string]string) ([]rename, error) { break } } + + // if there is a cycle, rename the remporary file if cycle { rs = append(rs, rename{tmp, dst}) }