Files
nlnieuws/internal/util/util.go
Peter Kleiweg a76fa21584 update
2026-06-05 16:05:46 +02:00

75 lines
1.6 KiB
Go

package util
import (
e "codeberg.org/pebbe/errors"
"fmt"
"os"
"path/filepath"
"regexp"
"strings"
)
var (
p = e.PanicErr
reEOL = regexp.MustCompile(`[.!?]['"”’]?$`)
reNEOL = regexp.MustCompile(`[.!?]['"”’]?\p{Lu}\p{Ll}+\.?`)
reLET = regexp.MustCompile(`\p{Lu}`)
reBody = regexp.MustCompile(`<[bB][rR][ /]*>`)
reQuotLeft = regexp.MustCompile(`<em>|<i>`)
reQuotRight = regexp.MustCompile(`</em>|</i>`)
)
func HtmlFix(html []byte) []byte {
html = reQuotLeft.ReplaceAllLiteral(html, []byte(" „"))
html = reQuotRight.ReplaceAllLiteral(html, []byte("” "))
return reBody.ReplaceAllLiteral(html, []byte(" "))
}
func HtmlFixString(html string) string {
html = reQuotLeft.ReplaceAllLiteralString(html, " „")
html = reQuotRight.ReplaceAllLiteralString(html, "” ")
return reBody.ReplaceAllLiteralString(html, " ")
}
func AddEnd(s string) string {
s = strings.TrimSpace(s)
if s == "" {
return ""
}
if reEOL.MatchString(s) {
return s + "\n"
}
return s + ".\n"
}
func FixSpace(s string, opt ...bool) string {
s = strings.Join(strings.Fields(s), " ")
if len(opt) > 0 && opt[0] {
s = reNEOL.ReplaceAllStringFunc(s, func(s1 string) string {
if strings.HasSuffix(s1, ".") {
// zoals: v.Chr.
return s1
}
i := reLET.FindStringIndex(s1)[0]
return s1[:i] + " " + s1[i:]
})
}
return s
}
func MkLock(filename string) {
pid := os.Getpid()
link := fmt.Sprintf("%s.%d", filepath.Base(filename), pid)
p(os.Symlink(link, filename))
name, err := os.Readlink(filename)
p(err)
if name != link {
p(fmt.Errorf("wrong lock name %q, should be %q", name, link))
}
}