Debian Codegraph @

helpers/general.go

raw
1 // Copyright 2019 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 helpers
15
16 import (
17 "fmt"
18 "io"
19 "net"
20 "os"
21 "path/filepath"
22 "slices"
23 "strings"
24 "unicode"
25 "unicode/utf8"
26
27 bp "github.com/gohugoio/hugo/bufferpool"
28
29 "github.com/spf13/afero"
30
31 "github.com/jdkato/prose/transform"
32 )
33
34 // FilePathSeparator as defined by os.Separator.
35 const FilePathSeparator = string(filepath.Separator)
36
37 // TCPListen starts listening on a valid TCP port.
38 func TCPListen() (net.Listener, *net.TCPAddr, error) {
39 l, err := net.Listen("tcp", ":0")
40 if err != nil {
41 return nil, nil, err
42 }
43 addr := l.Addr()
44 if a, ok := addr.(*net.TCPAddr); ok {
45 return l, a, nil
46 }
47 l.Close()
48 return nil, nil, fmt.Errorf("unable to obtain a valid tcp port: %v", addr)
49 }
50
51 // FirstLower returns s with the first Unicode letter mapped to lowercase.
52 func FirstLower(s string) string {
53 if s == "" {
54 return ""
55 }
56 r, n := utf8.DecodeRuneInString(s)
57 return string(unicode.ToLower(r)) + s[n:]
58 }
59
60 // FirstUpper returns s with the first Unicode letter mapped to uppercase.
61 func FirstUpper(s string) string {
62 if s == "" {
63 return ""
64 }
65 r, n := utf8.DecodeRuneInString(s)
66 return string(unicode.ToUpper(r)) + s[n:]
67 }
68
69 // ReaderToString reads from an io.Reader and returns its content as a string.
70 func ReaderToString(lines io.Reader) string {
71 if lines == nil {
72 return ""
73 }
74 b := bp.GetBuffer()
75 defer bp.PutBuffer(b)
76 b.ReadFrom(lines)
77 return b.String()
78 }
79
80 // GetTitleFunc returns a func that can be used to transform a string to
81 // title case.
82 //
83 // # The supported styles are
84 //
85 // - "Go" (strings.Title)
86 // - "AP" (see https://www.apstylebook.com/)
87 // - "Chicago" (see https://www.chicagomanualofstyle.org/home.html)
88 // - "FirstUpper" (only the first character is upper case)
89 // - "None" (no transformation)
90 //
91 // If an unknown or empty style is provided, AP style is what you get.
92 func GetTitleFunc(style string) func(s string) string {
93 switch strings.ToLower(style) {
94 case "go":
95 //lint:ignore SA1019 keep for now.
96 return strings.Title
97 case "chicago":
98 tc := transform.NewTitleConverter(transform.ChicagoStyle)
99 return tc.Title
100 case "none":
101 return func(s string) string { return s }
102 case "firstupper":
103 return FirstUpper
104 default:
105 tc := transform.NewTitleConverter(transform.APStyle)
106 return tc.Title
107 }
108 }
109
110 // HasStringsPrefix tests whether the string slice s begins with prefix slice s.
111 func HasStringsPrefix(s, prefix []string) bool {
112 return len(s) >= len(prefix) && compareStringSlices(s[0:len(prefix)], prefix)
113 }
114
115 // HasStringsSuffix tests whether the string slice s ends with suffix slice s.
116 func HasStringsSuffix(s, suffix []string) bool {
117 return len(s) >= len(suffix) && compareStringSlices(s[len(s)-len(suffix):], suffix)
118 }
119
120 func compareStringSlices(a, b []string) bool {
121 if a == nil && b == nil {
122 return true
123 }
124
125 if a == nil || b == nil {
126 return false
127 }
128
129 return slices.Equal(a, b)
130 }
131
132 // SliceToLower goes through the source slice and lowers all values.
133 func SliceToLower(s []string) []string {
134 if s == nil {
135 return nil
136 }
137
138 l := make([]string, len(s))
139 for i, v := range s {
140 l[i] = strings.ToLower(v)
141 }
142
143 return l
144 }
145
146 // StringSliceToList formats a string slice into a human-readable list.
147 // It joins the elements of the slice s with commas, using an Oxford comma,
148 // and precedes the final element with the conjunction c.
149 func StringSliceToList(s []string, c string) string {
150 const defaultConjunction = "and"
151
152 if c == "" {
153 c = defaultConjunction
154 }
155 if len(s) == 0 {
156 return ""
157 }
158 if len(s) == 1 {
159 return s[0]
160 }
161 if len(s) == 2 {
162 return fmt.Sprintf("%s %s %s", s[0], c, s[1])
163 }
164 return fmt.Sprintf("%s, %s %s", strings.Join(s[:len(s)-1], ", "), c, s[len(s)-1])
165 }
166
167 // IsWhitespace determines if the given rune is whitespace.
168 func IsWhitespace(r rune) bool {
169 return r == ' ' || r == '\t' || r == '\n' || r == '\r'
170 }
171
172 // PrintFs prints the given filesystem to the given writer starting from the given path.
173 // This is useful for debugging.
174 func PrintFs(fs afero.Fs, path string, w io.Writer) {
175 if fs == nil {
176 return
177 }
178
179 afero.Walk(fs, path, func(path string, info os.FileInfo, err error) error {
180 if err != nil {
181 panic(fmt.Sprintf("error: path %q: %s", path, err))
182 }
183 path = filepath.ToSlash(path)
184 if path == "" {
185 path = "."
186 }
187 fmt.Fprintln(w, path, info.IsDir())
188 return nil
189 })
190 }
191
192 // FormatByteCount pretty formats b.
193 func FormatByteCount(bc uint64) string {
194 const (
195 Gigabyte = 1 << 30
196 Megabyte = 1 << 20
197 Kilobyte = 1 << 10
198 )
199 switch {
200 case bc > Gigabyte || -bc > Gigabyte:
201 return fmt.Sprintf("%.2f GB", float64(bc)/Gigabyte)
202 case bc > Megabyte || -bc > Megabyte:
203 return fmt.Sprintf("%.2f MB", float64(bc)/Megabyte)
204 case bc > Kilobyte || -bc > Kilobyte:
205 return fmt.Sprintf("%.2f KB", float64(bc)/Kilobyte)
206 }
207 return fmt.Sprintf("%d B", bc)
208 }