Debian Codegraph @

tpl/strings/strings.go

raw
1 // Copyright 2017 The Hugo Authors. All rights reserved.
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 // http://www.apache.org/licenses/LICENSE-2.0
7 //
8 // Unless required by applicable law or agreed to in writing, software
9 // distributed under the License is distributed on an "AS IS" BASIS,
10 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
11 // See the License for the specific language governing permissions and
12 // limitations under the License.
13
14 // Package strings provides template functions for manipulating strings.
15 package strings
16
17 import (
18 "errors"
19 "fmt"
20 "html/template"
21 "regexp"
22 "strings"
23 "unicode"
24 "unicode/utf8"
25
26 "github.com/gohugoio/hugo/common/hmaps"
27 "github.com/gohugoio/hugo/common/hreflect"
28 "github.com/gohugoio/hugo/common/text"
29 "github.com/gohugoio/hugo/deps"
30 "github.com/gohugoio/hugo/helpers"
31 "github.com/gohugoio/hugo/tpl"
32 "github.com/rogpeppe/go-internal/diff"
33
34 "github.com/spf13/cast"
35 )
36
37 // New returns a new instance of the strings-namespaced template functions.
38 func New(d *deps.Deps) *Namespace {
39 return &Namespace{
40 deps: d,
41 replacerCache: hmaps.NewCacheWithOptions[string, *strings.Replacer](hmaps.CacheOptions{Size: 100}),
42 }
43 }
44
45 // Namespace provides template functions for the "strings" namespace.
46 // Most functions mimic the Go stdlib, but the order of the parameters may be
47 // different to ease their use in the Go template system.
48 type Namespace struct {
49 deps *deps.Deps
50 replacerCache *hmaps.Cache[string, *strings.Replacer]
51 }
52
53 // CountRunes returns the number of runes in s, excluding whitespace.
54 func (ns *Namespace) CountRunes(s any) (int, error) {
55 ss, err := cast.ToStringE(s)
56 if err != nil {
57 return 0, fmt.Errorf("failed to convert content to string: %w", err)
58 }
59
60 counter := 0
61 for _, r := range tpl.StripHTML(ss) {
62 if !helpers.IsWhitespace(r) {
63 counter++
64 }
65 }
66
67 return counter, nil
68 }
69
70 // RuneCount returns the number of runes in s.
71 func (ns *Namespace) RuneCount(s any) (int, error) {
72 ss, err := cast.ToStringE(s)
73 if err != nil {
74 return 0, fmt.Errorf("failed to convert content to string: %w", err)
75 }
76 return utf8.RuneCountInString(ss), nil
77 }
78
79 // CountWords returns the approximate word count in s.
80 func (ns *Namespace) CountWords(s any) (int, error) {
81 ss, err := cast.ToStringE(s)
82 if err != nil {
83 return 0, fmt.Errorf("failed to convert content to string: %w", err)
84 }
85
86 isCJKLanguage, err := regexp.MatchString(`\p{Han}|\p{Hangul}|\p{Hiragana}|\p{Katakana}`, ss)
87 if err != nil {
88 return 0, fmt.Errorf("failed to match regex pattern against string: %w", err)
89 }
90
91 if !isCJKLanguage {
92 return len(strings.Fields(tpl.StripHTML(ss))), nil
93 }
94
95 counter := 0
96 for word := range strings.FieldsSeq(tpl.StripHTML(ss)) {
97 runeCount := utf8.RuneCountInString(word)
98 if len(word) == runeCount {
99 counter++
100 } else {
101 counter += runeCount
102 }
103 }
104
105 return counter, nil
106 }
107
108 // Count counts the number of non-overlapping instances of substr in s.
109 // If substr is an empty string, Count returns 1 + the number of Unicode code points in s.
110 func (ns *Namespace) Count(substr, s any) (int, error) {
111 substrs, err := cast.ToStringE(substr)
112 if err != nil {
113 return 0, fmt.Errorf("failed to convert substr to string: %w", err)
114 }
115 ss, err := cast.ToStringE(s)
116 if err != nil {
117 return 0, fmt.Errorf("failed to convert s to string: %w", err)
118 }
119 return strings.Count(ss, substrs), nil
120 }
121
122 // Chomp returns a copy of s with all trailing newline characters removed.
123 func (ns *Namespace) Chomp(s any) (any, error) {
124 ss, err := cast.ToStringE(s)
125 if err != nil {
126 return "", err
127 }
128
129 res := text.Chomp(ss)
130 switch s.(type) {
131 case template.HTML:
132 return template.HTML(res), nil
133 default:
134 return res, nil
135 }
136 }
137
138 // Contains reports whether substr is in s.
139 func (ns *Namespace) Contains(s, substr any) (bool, error) {
140 ss, err := cast.ToStringE(s)
141 if err != nil {
142 return false, err
143 }
144
145 su, err := cast.ToStringE(substr)
146 if err != nil {
147 return false, err
148 }
149
150 return strings.Contains(ss, su), nil
151 }
152
153 // ContainsAny reports whether any Unicode code points in chars are within s.
154 func (ns *Namespace) ContainsAny(s, chars any) (bool, error) {
155 ss, err := cast.ToStringE(s)
156 if err != nil {
157 return false, err
158 }
159
160 sc, err := cast.ToStringE(chars)
161 if err != nil {
162 return false, err
163 }
164
165 return strings.ContainsAny(ss, sc), nil
166 }
167
168 // ContainsNonSpace reports whether s contains any non-space characters as defined
169 // by Unicode's White Space property,
170 // <docsmeta>{"newIn": "0.111.0" }</docsmeta>
171 func (ns *Namespace) ContainsNonSpace(s any) (bool, error) {
172 ss, err := cast.ToStringE(s)
173 if err != nil {
174 return false, err
175 }
176
177 for _, r := range ss {
178 if !unicode.IsSpace(r) {
179 return true, nil
180 }
181 }
182 return false, nil
183 }
184
185 // Diff returns an anchored diff of the two texts old and new in the “unified
186 // diff” format. If old and new are identical, Diff returns an empty string.
187 func (ns *Namespace) Diff(oldname string, old any, newname string, new any) (string, error) {
188 olds, err := cast.ToStringE(old)
189 if err != nil {
190 return "", err
191 }
192 news, err := cast.ToStringE(new)
193 if err != nil {
194 return "", err
195 }
196 return string(diff.Diff(oldname, []byte(olds), newname, []byte(news))), nil
197 }
198
199 // HasPrefix tests whether the input s begins with prefix.
200 func (ns *Namespace) HasPrefix(s, prefix any) (bool, error) {
201 ss, err := cast.ToStringE(s)
202 if err != nil {
203 return false, err
204 }
205
206 sx, err := cast.ToStringE(prefix)
207 if err != nil {
208 return false, err
209 }
210
211 return strings.HasPrefix(ss, sx), nil
212 }
213
214 // HasSuffix tests whether the input s begins with suffix.
215 func (ns *Namespace) HasSuffix(s, suffix any) (bool, error) {
216 ss, err := cast.ToStringE(s)
217 if err != nil {
218 return false, err
219 }
220
221 sx, err := cast.ToStringE(suffix)
222 if err != nil {
223 return false, err
224 }
225
226 return strings.HasSuffix(ss, sx), nil
227 }
228
229 // Replace returns a copy of the string s with all occurrences of old replaced
230 // with new. The number of replacements can be limited with an optional fourth
231 // parameter.
232 func (ns *Namespace) Replace(s, old, new any, limit ...any) (string, error) {
233 ss, err := cast.ToStringE(s)
234 if err != nil {
235 return "", err
236 }
237
238 so, err := cast.ToStringE(old)
239 if err != nil {
240 return "", err
241 }
242
243 sn, err := cast.ToStringE(new)
244 if err != nil {
245 return "", err
246 }
247
248 if len(limit) == 0 {
249 return strings.ReplaceAll(ss, so, sn), nil
250 }
251
252 lim, err := cast.ToIntE(limit[0])
253 if err != nil {
254 return "", err
255 }
256
257 return strings.Replace(ss, so, sn, lim), nil
258 }
259
260 // ReplacePairs returns a copy of a string with multiple replacements performed
261 // in a single pass. The last argument is the source string. Preceding arguments
262 // are old/new string pairs, either as a slice or as individual arguments.
263 func (ns *Namespace) ReplacePairs(args ...any) (string, error) {
264 if len(args) < 2 {
265 return "", fmt.Errorf("requires at least 2 arguments")
266 }
267
268 ss, err := cast.ToStringE(args[len(args)-1])
269 if err != nil {
270 return "", err
271 }
272
273 var p []string
274 if len(args) == 2 {
275 // slice form: ReplacePairs (slice "a" "b") "s"
276 if !hreflect.IsSlice(args[0]) {
277 return "", fmt.Errorf("with 2 arguments, the first must be a slice of replacement pairs, got %T", args[0])
278 }
279 p, err = cast.ToStringSliceE(args[0])
280 if err != nil {
281 return "", err
282 }
283 }
284 if p == nil {
285 // inline form: ReplacePairs "a" "b" "s"
286 p = make([]string, len(args)-1)
287 for i, v := range args[:len(args)-1] {
288 s, err := cast.ToStringE(v)
289 if err != nil {
290 return "", err
291 }
292 p[i] = s
293 }
294 }
295
296 if len(p) == 0 || ss == "" {
297 return ss, nil
298 }
299
300 if len(p)%2 != 0 {
301 return "", fmt.Errorf("uneven number of replacement pairs")
302 }
303
304 key := strings.Join(p, "\x00")
305 replacer, err := ns.replacerCache.GetOrCreate(key, func() (*strings.Replacer, error) {
306 return strings.NewReplacer(p...), nil
307 })
308 if err != nil {
309 return "", err
310 }
311
312 return replacer.Replace(ss), nil
313 }
314
315 // SliceString slices a string by specifying a half-open range with
316 // two indices, start and end. 1 and 4 creates a slice including elements 1 through 3.
317 // The end index can be omitted, it defaults to the string's length.
318 func (ns *Namespace) SliceString(a any, startEnd ...any) (string, error) {
319 aStr, err := cast.ToStringE(a)
320 if err != nil {
321 return "", err
322 }
323
324 var argStart, argEnd int
325
326 argNum := len(startEnd)
327
328 if argNum > 0 {
329 if argStart, err = cast.ToIntE(startEnd[0]); err != nil {
330 return "", errors.New("start argument must be integer")
331 }
332 }
333 if argNum > 1 {
334 if argEnd, err = cast.ToIntE(startEnd[1]); err != nil {
335 return "", errors.New("end argument must be integer")
336 }
337 }
338
339 if argNum > 2 {
340 return "", errors.New("too many arguments")
341 }
342
343 asRunes := []rune(aStr)
344
345 if argNum > 0 && (argStart < 0 || argStart >= len(asRunes)) {
346 return "", errors.New("slice bounds out of range")
347 }
348
349 if argNum == 2 {
350 if argEnd < 0 || argEnd > len(asRunes) {
351 return "", errors.New("slice bounds out of range")
352 }
353 return string(asRunes[argStart:argEnd]), nil
354 } else if argNum == 1 {
355 return string(asRunes[argStart:]), nil
356 } else {
357 return string(asRunes[:]), nil
358 }
359 }
360
361 // Split slices an input string into all substrings separated by delimiter.
362 func (ns *Namespace) Split(a any, delimiter string) ([]string, error) {
363 aStr, err := cast.ToStringE(a)
364 if err != nil {
365 return []string{}, err
366 }
367
368 return strings.Split(aStr, delimiter), nil
369 }
370
371 // Substr extracts parts of a string, beginning at the character at the specified
372 // position, and returns the specified number of characters.
373 //
374 // It normally takes two parameters: start and length.
375 // It can also take one parameter: start, i.e. length is omitted, in which case
376 // the substring starting from start until the end of the string will be returned.
377 //
378 // To extract characters from the end of the string, use a negative start number.
379 //
380 // In addition, borrowing from the extended behavior described at http://php.net/substr,
381 // if length is given and is negative, then that many characters will be omitted from
382 // the end of string.
383 func (ns *Namespace) Substr(a any, nums ...any) (string, error) {
384 s, err := cast.ToStringE(a)
385 if err != nil {
386 return "", err
387 }
388
389 asRunes := []rune(s)
390 rlen := len(asRunes)
391
392 var start, length int
393
394 switch len(nums) {
395 case 0:
396 return "", errors.New("too few arguments")
397 case 1:
398 if start, err = cast.ToIntE(nums[0]); err != nil {
399 return "", errors.New("start argument must be an integer")
400 }
401 length = rlen
402 case 2:
403 if start, err = cast.ToIntE(nums[0]); err != nil {
404 return "", errors.New("start argument must be an integer")
405 }
406 if length, err = cast.ToIntE(nums[1]); err != nil {
407 return "", errors.New("length argument must be an integer")
408 }
409 default:
410 return "", errors.New("too many arguments")
411 }
412
413 if rlen == 0 {
414 return "", nil
415 }
416
417 if start < 0 {
418 start += rlen
419 }
420
421 // start was originally negative beyond rlen
422 if start < 0 {
423 start = 0
424 }
425
426 if start > rlen-1 {
427 return "", nil
428 }
429
430 end := rlen
431
432 switch {
433 case length == 0:
434 return "", nil
435 case length < 0:
436 end += length
437 case length > 0:
438 end = start + length
439 }
440
441 if start >= end {
442 return "", nil
443 }
444
445 if end < 0 {
446 return "", nil
447 }
448
449 if end > rlen {
450 end = rlen
451 }
452
453 return string(asRunes[start:end]), nil
454 }
455
456 // Title returns a copy of the input s with all Unicode letters that begin words
457 // mapped to their title case.
458 func (ns *Namespace) Title(s any) (string, error) {
459 ss, err := cast.ToStringE(s)
460 if err != nil {
461 return "", err
462 }
463 return ns.deps.Conf.CreateTitle(ss), nil
464 }
465
466 // FirstLower returns s with the first Unicode letter mapped to lowercase.
467 func (ns *Namespace) FirstLower(s any) (string, error) {
468 ss, err := cast.ToStringE(s)
469 if err != nil {
470 return "", err
471 }
472
473 return helpers.FirstLower(ss), nil
474 }
475
476 // FirstUpper returns s with the first Unicode letter mapped to uppercase.
477 func (ns *Namespace) FirstUpper(s any) (string, error) {
478 ss, err := cast.ToStringE(s)
479 if err != nil {
480 return "", err
481 }
482
483 return helpers.FirstUpper(ss), nil
484 }
485
486 // ToLower returns s with all Unicode letters mapped to lowercase.
487 func (ns *Namespace) ToLower(s any) (string, error) {
488 ss, err := cast.ToStringE(s)
489 if err != nil {
490 return "", err
491 }
492
493 return strings.ToLower(ss), nil
494 }
495
496 // ToUpper returns s with all Unicode letters mapped to uppercase.
497 func (ns *Namespace) ToUpper(s any) (string, error) {
498 ss, err := cast.ToStringE(s)
499 if err != nil {
500 return "", err
501 }
502
503 return strings.ToUpper(ss), nil
504 }
505
506 // Trim returns converts the strings s removing all leading and trailing characters defined
507 // contained.
508 func (ns *Namespace) Trim(s, cutset any) (string, error) {
509 ss, err := cast.ToStringE(s)
510 if err != nil {
511 return "", err
512 }
513
514 sc, err := cast.ToStringE(cutset)
515 if err != nil {
516 return "", err
517 }
518
519 return strings.Trim(ss, sc), nil
520 }
521
522 // TrimSpace returns the given string, removing leading and trailing whitespace
523 // as defined by Unicode.
524 func (ns *Namespace) TrimSpace(s any) (string, error) {
525 ss, err := cast.ToStringE(s)
526 if err != nil {
527 return "", err
528 }
529
530 return strings.TrimSpace(ss), nil
531 }
532
533 // TrimLeft returns a slice of the string s with all leading characters
534 // contained in cutset removed.
535 func (ns *Namespace) TrimLeft(cutset, s any) (string, error) {
536 ss, err := cast.ToStringE(s)
537 if err != nil {
538 return "", err
539 }
540
541 sc, err := cast.ToStringE(cutset)
542 if err != nil {
543 return "", err
544 }
545
546 return strings.TrimLeft(ss, sc), nil
547 }
548
549 // TrimPrefix returns s without the provided leading prefix string. If s doesn't
550 // start with prefix, s is returned unchanged.
551 func (ns *Namespace) TrimPrefix(prefix, s any) (string, error) {
552 ss, err := cast.ToStringE(s)
553 if err != nil {
554 return "", err
555 }
556
557 sx, err := cast.ToStringE(prefix)
558 if err != nil {
559 return "", err
560 }
561
562 return strings.TrimPrefix(ss, sx), nil
563 }
564
565 // TrimRight returns a slice of the string s with all trailing characters
566 // contained in cutset removed.
567 func (ns *Namespace) TrimRight(cutset, s any) (string, error) {
568 ss, err := cast.ToStringE(s)
569 if err != nil {
570 return "", err
571 }
572
573 sc, err := cast.ToStringE(cutset)
574 if err != nil {
575 return "", err
576 }
577
578 return strings.TrimRight(ss, sc), nil
579 }
580
581 // TrimSuffix returns s without the provided trailing suffix string. If s
582 // doesn't end with suffix, s is returned unchanged.
583 func (ns *Namespace) TrimSuffix(suffix, s any) (string, error) {
584 ss, err := cast.ToStringE(s)
585 if err != nil {
586 return "", err
587 }
588
589 sx, err := cast.ToStringE(suffix)
590 if err != nil {
591 return "", err
592 }
593
594 return strings.TrimSuffix(ss, sx), nil
595 }
596
597 // Repeat returns a new string consisting of n copies of the string s.
598 func (ns *Namespace) Repeat(n, s any) (string, error) {
599 ss, err := cast.ToStringE(s)
600 if err != nil {
601 return "", err
602 }
603
604 sn, err := cast.ToIntE(n)
605 if err != nil {
606 return "", err
607 }
608
609 if sn < 0 {
610 return "", errors.New("strings: negative Repeat count")
611 }
612
613 return strings.Repeat(ss, sn), nil
614 }