49 lines
1.9 KiB
Go
49 lines
1.9 KiB
Go
// SPDX-License-Identifier: GPL-3.0-or-later
|
||
|
||
// Package content loads the pages and the news of a site from Markdown files
|
||
// and works out their addresses.
|
||
package content
|
||
|
||
import (
|
||
"fmt"
|
||
"regexp"
|
||
"strings"
|
||
)
|
||
|
||
// Category is a news category: the name as written and the name used in its
|
||
// address.
|
||
type Category struct {
|
||
// Name is the category as written in the header of a news file.
|
||
Name string
|
||
// Slug is the name in the address, such as "linux-day".
|
||
Slug string
|
||
}
|
||
|
||
// accents maps the accented letters of the Latin alphabets to ASCII, so a
|
||
// category address stays readable without an extra dependency.
|
||
var accents = strings.NewReplacer(
|
||
"à", "a", "á", "a", "â", "a", "ã", "a", "ä", "a", "å", "a", "ā", "a", "ă", "a", "ą", "a",
|
||
"æ", "ae", "ç", "c", "ć", "c", "č", "c", "ď", "d", "đ", "d",
|
||
"è", "e", "é", "e", "ê", "e", "ë", "e", "ē", "e", "ė", "e", "ę", "e", "ě", "e",
|
||
"ğ", "g", "ì", "i", "í", "i", "î", "i", "ï", "i", "ī", "i", "į", "i", "ı", "i",
|
||
"ł", "l", "ñ", "n", "ń", "n", "ň", "n",
|
||
"ò", "o", "ó", "o", "ô", "o", "õ", "o", "ö", "o", "ø", "o", "ō", "o", "ő", "o", "œ", "oe",
|
||
"ř", "r", "ś", "s", "š", "s", "ş", "s", "ß", "ss", "ť", "t", "ț", "t",
|
||
"ù", "u", "ú", "u", "û", "u", "ü", "u", "ū", "u", "ů", "u", "ű", "u",
|
||
"ý", "y", "ÿ", "y", "ź", "z", "ž", "z", "ż", "z",
|
||
)
|
||
|
||
// nonSlug matches a run of characters that cannot be part of an address.
|
||
var nonSlug = regexp.MustCompile(`[^a-z0-9]+`)
|
||
|
||
// CategorySlug turns a category name into the name used in its address:
|
||
// lowercase, without accents, with hyphens between words ("Linux Day" becomes
|
||
// "linux-day"). A name without any letter or digit is an error.
|
||
func CategorySlug(name string) (string, error) {
|
||
slug := nonSlug.ReplaceAllString(accents.Replace(strings.ToLower(name)), "-")
|
||
slug = strings.Trim(slug, "-")
|
||
if slug == "" {
|
||
return "", fmt.Errorf("category %q has no letters or digits", name)
|
||
}
|
||
return slug, nil
|
||
}
|