]> git.maquefel.me Git - brevno-suite/hugo/commitdiff
metrics: Fix divide by zero error
authorCameron Moore <moorereason@gmail.com>
Thu, 26 May 2022 02:14:37 +0000 (21:14 -0500)
committerBjørn Erik Pedersen <bjorn.erik.pedersen@gmail.com>
Thu, 26 May 2022 08:39:29 +0000 (10:39 +0200)
Under certain conditions, `howSimilarString` could reach a divide-by-
zero situation which causes bogus values to print in the cache potential
column of the template hints output.  This situation essentially causes
a `int(math.NaN())` value to be returned and hilarity ensues thereafter.

metrics/metrics.go
metrics/metrics_test.go

index 9c46fdf7ee31d068a9747f85a687cc46baf8c5cd..c57b1177d12009a781710b1de0e1932ca4cab371 100644 (file)
@@ -281,6 +281,10 @@ func howSimilarStrings(a, b string) int {
                }
        }
 
+       if common == 0 && common == len(af) {
+               return 100
+       }
+
        return int(math.Floor((float64(common) / float64(len(af)) * 100)))
 }
 
index d8c3237f85a41e6b935115f0f408065205abaddd..6e799a393134cc7601f55e98526d2e62593aa2a7 100644 (file)
@@ -43,6 +43,7 @@ func TestSimilarPercentage(t *testing.T) {
        c.Assert(howSimilar(template.HTML("Hugo Rules"), template.HTML("Hugo Rules")), qt.Equals, 100)
        c.Assert(howSimilar(map[string]any{"a": 32, "b": 33}, map[string]any{"a": 32, "b": 33}), qt.Equals, 100)
        c.Assert(howSimilar(map[string]any{"a": 32, "b": 33}, map[string]any{"a": 32, "b": 34}), qt.Equals, 0)
+       c.Assert(howSimilar("\n", ""), qt.Equals, 100)
 }
 
 type testStruct struct {