From 12779560ca8b1fe200f6261967c88d020d1d4fc2 Mon Sep 17 00:00:00 2001 From: ionutboangiu Date: Tue, 17 Oct 2023 03:13:58 -0400 Subject: [PATCH] Handle empty relative path case in HP.AsString() Return '.' when HierarchyPath is empty and prefix is false. --- utils/coreutils.go | 12 +++++++----- utils/coreutils_test.go | 4 ++-- 2 files changed, 9 insertions(+), 7 deletions(-) diff --git a/utils/coreutils.go b/utils/coreutils.go index 49ba25ce6..2021b69bb 100644 --- a/utils/coreutils.go +++ b/utils/coreutils.go @@ -687,18 +687,20 @@ func (hP HierarchyPath) AsString(sep string, prefix bool) string { var strHP strings.Builder // If prefix is true and the HierarchyPath slice is empty, sep will be returned. + // This will indicate the start of the absolute path. if prefix { strHP.WriteString(sep) } - // TODO: Since this function can convert both the full and the relative HierarchyPath to a string, with - // prefix telling us which is which (true -> full path, false -> relative path), we should consider - // returning the '.' character when prefix == false. Currently, because we are returning an empty string - // if the path we are currently parsing is equal to the root path, when we attempt to retrieve the element - // we receive the error "expr expression is nil". if len(hP) == 0 { + // If prefix is false and HierarchyPath is empty, return '.' to represent the current directory in a relative path. + // This convention avoids errors (e.g., "expr expression is nil") when retrieving elements from an empty path. + if !prefix { + return "." + } return strHP.String() } + for i, elem := range hP { if i != 0 { strHP.WriteString(sep) diff --git a/utils/coreutils_test.go b/utils/coreutils_test.go index 67de2a51f..852e01fd3 100644 --- a/utils/coreutils_test.go +++ b/utils/coreutils_test.go @@ -1016,7 +1016,7 @@ func TestHierarchyPathAsString(t *testing.T) { hP: HierarchyPath{}, sep: "/", prefix: false, - expected: "", + expected: ".", }, { name: "Empty HierarchyPath with prefix", @@ -1072,7 +1072,7 @@ func TestHierarchyPathAsString(t *testing.T) { for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { if received := tt.hP.AsString(tt.sep, tt.prefix); received != tt.expected { - t.Errorf("expected %s, received %s", tt.expected, received) + t.Errorf("expected <%s>, received <%s>", tt.expected, received) } }) }