Use cases.Title and replace - and _ with spaces

This commit is contained in:
Dennis Verheijden 2025-09-11 13:46:33 +02:00 committed by Manuel Rüger
parent 6d81045bf0
commit ff677a8690
2 changed files with 32 additions and 4 deletions

View File

@ -10,6 +10,8 @@ import (
"strings"
"github.com/reconquest/pkg/log"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
const (
@ -82,8 +84,7 @@ func ExtractMeta(data []byte, spaceFromCli string, titleFromH1 bool, titleFromFi
meta.ContentAppearance = FullWidthContentAppearance // Default to full-width for backwards compatibility
}
//nolint:staticcheck
header := strings.Title(matches[1])
header := cases.Title(language.English).String(matches[1])
var value string
if len(matches) > 1 {
@ -193,7 +194,10 @@ func ExtractMeta(data []byte, spaceFromCli string, titleFromH1 bool, titleFromFi
func setTitleFromFilename(meta *Meta, filename string) {
base := filepath.Base(filename)
meta.Title = strings.TrimSuffix(base, filepath.Ext(base))
title := strings.TrimSuffix(base, filepath.Ext(base))
title = strings.ReplaceAll(title, "_", " ")
title = strings.ReplaceAll(title, "-", " ")
meta.Title = cases.Title(language.English).String(title)
}
// ExtractDocumentLeadingH1 will extract leading H1 heading

View File

@ -33,6 +33,30 @@ func TestSetTitleFromFilename(t *testing.T) {
t.Run("set title from filename", func(t *testing.T) {
meta := &Meta{Title: ""}
setTitleFromFilename(meta, "/path/to/test.md")
assert.Equal(t, "test", meta.Title)
assert.Equal(t, "Test", meta.Title)
})
t.Run("replace underscores with spaces", func(t *testing.T) {
meta := &Meta{Title: ""}
setTitleFromFilename(meta, "/path/to/test_with_underscores.md")
assert.Equal(t, "Test With Underscores", meta.Title)
})
t.Run("replace dashes with spaces", func(t *testing.T) {
meta := &Meta{Title: ""}
setTitleFromFilename(meta, "/path/to/test-with-dashes.md")
assert.Equal(t, "Test With Dashes", meta.Title)
})
t.Run("mixed underscores and dashes", func(t *testing.T) {
meta := &Meta{Title: ""}
setTitleFromFilename(meta, "/path/to/test_with-mixed_separators.md")
assert.Equal(t, "Test With Mixed Separators", meta.Title)
})
t.Run("already title cased", func(t *testing.T) {
meta := &Meta{Title: ""}
setTitleFromFilename(meta, "/path/to/Already-Title-Cased.md")
assert.Equal(t, "Already Title Cased", meta.Title)
})
}