From 5b829f1d8238dd8db3740525ea5307d9e3e66c6f Mon Sep 17 00:00:00 2001 From: Timur Ismagilov Date: Fri, 1 Jul 2022 19:22:54 +0500 Subject: [PATCH] Categories: Move them when a hypha is renamed --- categories/categories.go | 16 ++++++++++++++++ shroom/rename.go | 10 ++++++++-- 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/categories/categories.go b/categories/categories.go index 50ab12b..61d1345 100644 --- a/categories/categories.go +++ b/categories/categories.go @@ -94,3 +94,19 @@ func removeHyphaFromCategory(hyphaName, catName string) { mutex.Unlock() go saveToDisk() } + +// RenameHyphaInAllCategories finds all mentions of oldName and replaces them with newName. Pass canonical names. Make sure newName is not taken. If oldName is not in any category, RenameHyphaInAllCategories is a no-op. +func RenameHyphaInAllCategories(oldName, newName string) { + mutex.Lock() + defer mutex.Unlock() + if node, ok := hyphaToCategories[oldName]; ok { + hyphaToCategories[newName] = node + delete(hyphaToCategories, oldName) // node should still be in memory 🙏 + for _, catName := range node.categoryList { + if catNode, ok := categoryToHyphae[catName]; ok { + catNode.removeHypha(oldName) + catNode.storeHypha(newName) + } + } + } +} diff --git a/shroom/rename.go b/shroom/rename.go index 71b4e9c..fc22fe6 100644 --- a/shroom/rename.go +++ b/shroom/rename.go @@ -4,6 +4,7 @@ import ( "errors" "fmt" "github.com/bouncepaw/mycorrhiza/backlinks" + "github.com/bouncepaw/mycorrhiza/categories" "regexp" "github.com/bouncepaw/mycorrhiza/history" @@ -36,6 +37,7 @@ func Rename(oldHypha hyphae.ExistingHypha, newName string, recursive bool, u *us var ( re = regexp.MustCompile(`(?i)` + oldHypha.CanonicalName()) replaceName = func(str string) string { + // Can we drop that util.CanonicalName? return re.ReplaceAllString(util.CanonicalName(str), newName) } hyphaeToRename = findHyphaeToRename(oldHypha, recursive) @@ -67,9 +69,13 @@ func Rename(oldHypha hyphae.ExistingHypha, newName string, recursive bool, u *us } for _, h := range hyphaeToRename { - oldName := h.CanonicalName() - hyphae.RenameHyphaTo(h, replaceName(h.CanonicalName()), replaceName) + var ( + oldName = h.CanonicalName() + newName = replaceName(oldName) + ) + hyphae.RenameHyphaTo(h, newName, replaceName) backlinks.UpdateBacklinksAfterRename(h, oldName) + categories.RenameHyphaInAllCategories(oldName, newName) } return nil