refactor: extract TruncateRunes function for safe string truncation with suffix
Signed-off-by: Deluan <deluan@navidrome.org> # Conflicts: # core/share.go # core/share_test.go
This commit is contained in:
+2
-15
@@ -13,6 +13,7 @@ import (
|
||||
"github.com/navidrome/navidrome/model"
|
||||
. "github.com/navidrome/navidrome/utils/gg"
|
||||
"github.com/navidrome/navidrome/utils/slice"
|
||||
"github.com/navidrome/navidrome/utils/str"
|
||||
)
|
||||
|
||||
type Share interface {
|
||||
@@ -120,21 +121,7 @@ func (r *shareRepositoryWrapper) Save(entity interface{}) (string, error) {
|
||||
return "", model.ErrNotFound
|
||||
}
|
||||
|
||||
const maxContentRunes = 30
|
||||
const truncateToRunes = 26
|
||||
|
||||
var runeCount int
|
||||
var truncateIndex int
|
||||
for i := range s.Contents {
|
||||
runeCount++
|
||||
if runeCount == truncateToRunes+1 {
|
||||
truncateIndex = i
|
||||
}
|
||||
}
|
||||
|
||||
if runeCount > maxContentRunes {
|
||||
s.Contents = s.Contents[:truncateIndex] + "..."
|
||||
}
|
||||
s.Contents = str.TruncateRunes(s.Contents, 30, "...")
|
||||
|
||||
id, err = r.Persistable.Save(s)
|
||||
return id, err
|
||||
|
||||
+2
-2
@@ -52,7 +52,7 @@ var _ = Describe("Share", func() {
|
||||
entity := &model.Share{Description: "test", ResourceIDs: "789"}
|
||||
_, err := repo.Save(entity)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(entity.Contents).To(Equal("Example Media File But The..."))
|
||||
Expect(entity.Contents).To(Equal("Example Media File But The ..."))
|
||||
})
|
||||
|
||||
It("does not truncate CJK labels shorter than 30 runes", func() {
|
||||
@@ -68,7 +68,7 @@ var _ = Describe("Share", func() {
|
||||
entity := &model.Share{Description: "test", ResourceIDs: "789"}
|
||||
_, err := repo.Save(entity)
|
||||
Expect(err).ToNot(HaveOccurred())
|
||||
Expect(entity.Contents).To(Equal("私の中の幻想的世界観及びその顕現を想起させたある現実..."))
|
||||
Expect(entity.Contents).To(Equal("私の中の幻想的世界観及びその顕現を想起させたある現実で..."))
|
||||
})
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user