add comments to the main logic

This commit is contained in:
itchyny 2020-01-08 10:27:20 +09:00
parent e306b90e00
commit 1bb8c86761

22
mmv.go
View file

@ -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})
}