61 lines
1.7 KiB
Go
61 lines
1.7 KiB
Go
package database
|
||
|
||
import (
|
||
"regexp"
|
||
"strconv"
|
||
"strings"
|
||
)
|
||
|
||
const (
|
||
snapshotMaxRunes = 100
|
||
snapshotFallbackSlug = "article"
|
||
)
|
||
|
||
var snapshotNonSlugRun = regexp.MustCompile(`[^a-z0-9]+`)
|
||
|
||
var snapshotFolder = strings.NewReplacer(
|
||
"à", "a", "á", "a", "â", "a", "ã", "a", "ä", "a", "å", "a", "ā", "a", "ă", "a", "ą", "a",
|
||
"æ", "ae",
|
||
"ç", "c", "ć", "c", "č", "c", "ĉ", "c",
|
||
"ď", "d", "đ", "d",
|
||
"è", "e", "é", "e", "ê", "e", "ë", "e", "ē", "e", "ė", "e", "ę", "e", "ě", "e",
|
||
"ğ", "g",
|
||
"ì", "i", "í", "i", "î", "i", "ï", "i", "ī", "i", "į", "i", "ı", "i",
|
||
"ł", "l", "ľ", "l",
|
||
"ñ", "n", "ń", "n", "ň", "n",
|
||
"ò", "o", "ó", "o", "ô", "o", "õ", "o", "ö", "o", "ø", "o", "ō", "o", "ő", "o",
|
||
"œ", "oe",
|
||
"ř", "r",
|
||
"ś", "s", "š", "s", "ş", "s", "ș", "s",
|
||
"ß", "ss",
|
||
"ť", "t", "ț", "t", "ţ", "t",
|
||
"ù", "u", "ú", "u", "û", "u", "ü", "u", "ū", "u", "ů", "u", "ű", "u", "ų", "u",
|
||
"ý", "y", "ÿ", "y",
|
||
"ź", "z", "ż", "z", "ž", "z",
|
||
)
|
||
|
||
func snapshotSlug(text string) string {
|
||
folded := snapshotFolder.Replace(strings.ToLower(text))
|
||
generated := strings.Trim(snapshotNonSlugRun.ReplaceAllString(folded, "-"), "-")
|
||
generated = snapshotTruncate(generated, snapshotMaxRunes)
|
||
if generated == "" {
|
||
return snapshotFallbackSlug
|
||
}
|
||
return generated
|
||
}
|
||
|
||
func snapshotSlugWithSuffix(base string, attempt int) string {
|
||
if attempt <= 1 {
|
||
return base
|
||
}
|
||
suffix := "-" + strconv.Itoa(attempt)
|
||
return snapshotTruncate(base, snapshotMaxRunes-len(suffix)) + suffix
|
||
}
|
||
|
||
func snapshotTruncate(candidate string, limit int) string {
|
||
if len(candidate) <= limit {
|
||
return candidate
|
||
}
|
||
return strings.TrimRight(candidate[:limit], "-")
|
||
}
|