mirror of
https://github.com/gohugoio/hugo.git
synced 2024-12-23 23:20:49 +00:00
79d9f82e79
It started with wanting to move templates in template bundles and the rest followed. I did my best to start grouping related functions together, but there are some that I missed. There is also the method Urlize that seems to be a special function used in both worlds. I'll need to revisit this method.
75 lines
1.6 KiB
Go
75 lines
1.6 KiB
Go
package hugolib
|
|
|
|
import (
|
|
"bytes"
|
|
"fmt"
|
|
"os/exec"
|
|
"strings"
|
|
)
|
|
|
|
var summaryLength = 70
|
|
var summaryDivider = []byte("<!--more-->")
|
|
|
|
func TotalWords(s string) int {
|
|
return len(strings.Fields(s))
|
|
}
|
|
|
|
func WordCount(s string) map[string]int {
|
|
m := make(map[string]int)
|
|
for _, f := range strings.Fields(s) {
|
|
m[f] += 1
|
|
}
|
|
|
|
return m
|
|
}
|
|
|
|
func RemoveSummaryDivider(content []byte) []byte {
|
|
return bytes.Replace(content, summaryDivider, []byte(""), -1)
|
|
}
|
|
|
|
func TruncateWords(s string, max int) string {
|
|
words := strings.Fields(s)
|
|
if max > len(words) {
|
|
return strings.Join(words, " ")
|
|
}
|
|
|
|
return strings.Join(words[:max], " ")
|
|
}
|
|
|
|
func TruncateWordsToWholeSentence(s string, max int) string {
|
|
words := strings.Fields(s)
|
|
if max > len(words) {
|
|
return strings.Join(words, " ")
|
|
}
|
|
|
|
for counter, word := range words[max:] {
|
|
if strings.HasSuffix(word, ".") ||
|
|
strings.HasSuffix(word, "?") ||
|
|
strings.HasSuffix(word, ".\"") ||
|
|
strings.HasSuffix(word, "!") {
|
|
return strings.Join(words[:max+counter+1], " ")
|
|
}
|
|
}
|
|
|
|
return strings.Join(words[:max], " ")
|
|
}
|
|
|
|
func getRstContent(content []byte) string {
|
|
cleanContent := bytes.Replace(content, summaryDivider, []byte(""), 1)
|
|
|
|
cmd := exec.Command("rst2html.py", "--leave-comments")
|
|
cmd.Stdin = bytes.NewReader(cleanContent)
|
|
var out bytes.Buffer
|
|
cmd.Stdout = &out
|
|
if err := cmd.Run(); err != nil {
|
|
fmt.Println(err)
|
|
}
|
|
|
|
rstLines := strings.Split(out.String(), "\n")
|
|
for i, line := range rstLines {
|
|
if strings.HasPrefix(line, "<body>") {
|
|
rstLines = (rstLines[i+1 : len(rstLines)-3])
|
|
}
|
|
}
|
|
return strings.Join(rstLines, "\n")
|
|
}
|