From 2823a7cff045efde2ef507387c5ebb6d2b08d014 Mon Sep 17 00:00:00 2001 From: Stefan Haller Date: Sun, 1 Dec 2024 17:29:43 +0100 Subject: [PATCH] Make equalHash more correct So far it didn't have to handle the case where one hash is empty and the other isn't, but in the next commit we need that, so let's handle that case correctly. There's enough logic in the function now that it's worth covering it with tests. --- pkg/utils/rebase_todo.go | 7 ++++++- pkg/utils/rebase_todo_test.go | 24 ++++++++++++++++++++++++ 2 files changed, 30 insertions(+), 1 deletion(-) diff --git a/pkg/utils/rebase_todo.go b/pkg/utils/rebase_todo.go index d08bd1bef..993d90005 100644 --- a/pkg/utils/rebase_todo.go +++ b/pkg/utils/rebase_todo.go @@ -56,7 +56,12 @@ func EditRebaseTodo(filePath string, changes []TodoChange, commentChar byte) err } func equalHash(a, b string) bool { - return strings.HasPrefix(a, b) || strings.HasPrefix(b, a) + if len(a) == 0 && len(b) == 0 { + return true + } + + commonLength := min(len(a), len(b)) + return commonLength > 0 && a[:commonLength] == b[:commonLength] } func findTodo(todos []todo.Todo, todoToFind Todo) (int, bool) { diff --git a/pkg/utils/rebase_todo_test.go b/pkg/utils/rebase_todo_test.go index fbcc82d20..0c56e3bea 100644 --- a/pkg/utils/rebase_todo_test.go +++ b/pkg/utils/rebase_todo_test.go @@ -2,6 +2,7 @@ package utils import ( "errors" + "fmt" "testing" "github.com/stefanhaller/git-todo-parser/todo" @@ -453,3 +454,26 @@ func TestRebaseCommands_deleteTodos(t *testing.T) { }) } } + +func Test_equalHash(t *testing.T) { + scenarios := []struct { + a string + b string + expected bool + }{ + {"", "", true}, + {"", "123", false}, + {"123", "", false}, + {"123", "123", true}, + {"123", "123abc", true}, + {"123abc", "123", true}, + {"123", "a", false}, + {"1", "abc", false}, + } + + for _, scenario := range scenarios { + t.Run(fmt.Sprintf("'%s' vs. '%s'", scenario.a, scenario.b), func(t *testing.T) { + assert.Equal(t, scenario.expected, equalHash(scenario.a, scenario.b)) + }) + } +}