podman
270 строк · 7.8 Кб
1package govalidator
2
3import (
4"errors"
5"fmt"
6"html"
7"math"
8"path"
9"regexp"
10"strings"
11"unicode"
12"unicode/utf8"
13)
14
15// Contains checks if the string contains the substring.
16func Contains(str, substring string) bool {
17return strings.Contains(str, substring)
18}
19
20// Matches checks if string matches the pattern (pattern is regular expression)
21// In case of error return false
22func Matches(str, pattern string) bool {
23match, _ := regexp.MatchString(pattern, str)
24return match
25}
26
27// LeftTrim trims characters from the left side of the input.
28// If second argument is empty, it will remove leading spaces.
29func LeftTrim(str, chars string) string {
30if chars == "" {
31return strings.TrimLeftFunc(str, unicode.IsSpace)
32}
33r, _ := regexp.Compile("^[" + chars + "]+")
34return r.ReplaceAllString(str, "")
35}
36
37// RightTrim trims characters from the right side of the input.
38// If second argument is empty, it will remove trailing spaces.
39func RightTrim(str, chars string) string {
40if chars == "" {
41return strings.TrimRightFunc(str, unicode.IsSpace)
42}
43r, _ := regexp.Compile("[" + chars + "]+$")
44return r.ReplaceAllString(str, "")
45}
46
47// Trim trims characters from both sides of the input.
48// If second argument is empty, it will remove spaces.
49func Trim(str, chars string) string {
50return LeftTrim(RightTrim(str, chars), chars)
51}
52
53// WhiteList removes characters that do not appear in the whitelist.
54func WhiteList(str, chars string) string {
55pattern := "[^" + chars + "]+"
56r, _ := regexp.Compile(pattern)
57return r.ReplaceAllString(str, "")
58}
59
60// BlackList removes characters that appear in the blacklist.
61func BlackList(str, chars string) string {
62pattern := "[" + chars + "]+"
63r, _ := regexp.Compile(pattern)
64return r.ReplaceAllString(str, "")
65}
66
67// StripLow removes characters with a numerical value < 32 and 127, mostly control characters.
68// If keep_new_lines is true, newline characters are preserved (\n and \r, hex 0xA and 0xD).
69func StripLow(str string, keepNewLines bool) string {
70chars := ""
71if keepNewLines {
72chars = "\x00-\x09\x0B\x0C\x0E-\x1F\x7F"
73} else {
74chars = "\x00-\x1F\x7F"
75}
76return BlackList(str, chars)
77}
78
79// ReplacePattern replaces regular expression pattern in string
80func ReplacePattern(str, pattern, replace string) string {
81r, _ := regexp.Compile(pattern)
82return r.ReplaceAllString(str, replace)
83}
84
85// Escape replaces <, >, & and " with HTML entities.
86var Escape = html.EscapeString
87
88func addSegment(inrune, segment []rune) []rune {
89if len(segment) == 0 {
90return inrune
91}
92if len(inrune) != 0 {
93inrune = append(inrune, '_')
94}
95inrune = append(inrune, segment...)
96return inrune
97}
98
99// UnderscoreToCamelCase converts from underscore separated form to camel case form.
100// Ex.: my_func => MyFunc
101func UnderscoreToCamelCase(s string) string {
102return strings.Replace(strings.Title(strings.Replace(strings.ToLower(s), "_", " ", -1)), " ", "", -1)
103}
104
105// CamelCaseToUnderscore converts from camel case form to underscore separated form.
106// Ex.: MyFunc => my_func
107func CamelCaseToUnderscore(str string) string {
108var output []rune
109var segment []rune
110for _, r := range str {
111
112// not treat number as separate segment
113if !unicode.IsLower(r) && string(r) != "_" && !unicode.IsNumber(r) {
114output = addSegment(output, segment)
115segment = nil
116}
117segment = append(segment, unicode.ToLower(r))
118}
119output = addSegment(output, segment)
120return string(output)
121}
122
123// Reverse returns reversed string
124func Reverse(s string) string {
125r := []rune(s)
126for i, j := 0, len(r)-1; i < j; i, j = i+1, j-1 {
127r[i], r[j] = r[j], r[i]
128}
129return string(r)
130}
131
132// GetLines splits string by "\n" and return array of lines
133func GetLines(s string) []string {
134return strings.Split(s, "\n")
135}
136
137// GetLine returns specified line of multiline string
138func GetLine(s string, index int) (string, error) {
139lines := GetLines(s)
140if index < 0 || index >= len(lines) {
141return "", errors.New("line index out of bounds")
142}
143return lines[index], nil
144}
145
146// RemoveTags removes all tags from HTML string
147func RemoveTags(s string) string {
148return ReplacePattern(s, "<[^>]*>", "")
149}
150
151// SafeFileName returns safe string that can be used in file names
152func SafeFileName(str string) string {
153name := strings.ToLower(str)
154name = path.Clean(path.Base(name))
155name = strings.Trim(name, " ")
156separators, err := regexp.Compile(`[ &_=+:]`)
157if err == nil {
158name = separators.ReplaceAllString(name, "-")
159}
160legal, err := regexp.Compile(`[^[:alnum:]-.]`)
161if err == nil {
162name = legal.ReplaceAllString(name, "")
163}
164for strings.Contains(name, "--") {
165name = strings.Replace(name, "--", "-", -1)
166}
167return name
168}
169
170// NormalizeEmail canonicalize an email address.
171// The local part of the email address is lowercased for all domains; the hostname is always lowercased and
172// the local part of the email address is always lowercased for hosts that are known to be case-insensitive (currently only GMail).
173// Normalization follows special rules for known providers: currently, GMail addresses have dots removed in the local part and
174// are stripped of tags (e.g. some.one+tag@gmail.com becomes someone@gmail.com) and all @googlemail.com addresses are
175// normalized to @gmail.com.
176func NormalizeEmail(str string) (string, error) {
177if !IsEmail(str) {
178return "", fmt.Errorf("%s is not an email", str)
179}
180parts := strings.Split(str, "@")
181parts[0] = strings.ToLower(parts[0])
182parts[1] = strings.ToLower(parts[1])
183if parts[1] == "gmail.com" || parts[1] == "googlemail.com" {
184parts[1] = "gmail.com"
185parts[0] = strings.Split(ReplacePattern(parts[0], `\.`, ""), "+")[0]
186}
187return strings.Join(parts, "@"), nil
188}
189
190// Truncate a string to the closest length without breaking words.
191func Truncate(str string, length int, ending string) string {
192var aftstr, befstr string
193if len(str) > length {
194words := strings.Fields(str)
195before, present := 0, 0
196for i := range words {
197befstr = aftstr
198before = present
199aftstr = aftstr + words[i] + " "
200present = len(aftstr)
201if present > length && i != 0 {
202if (length - before) < (present - length) {
203return Trim(befstr, " /\\.,\"'#!?&@+-") + ending
204}
205return Trim(aftstr, " /\\.,\"'#!?&@+-") + ending
206}
207}
208}
209
210return str
211}
212
213// PadLeft pads left side of a string if size of string is less then indicated pad length
214func PadLeft(str string, padStr string, padLen int) string {
215return buildPadStr(str, padStr, padLen, true, false)
216}
217
218// PadRight pads right side of a string if size of string is less then indicated pad length
219func PadRight(str string, padStr string, padLen int) string {
220return buildPadStr(str, padStr, padLen, false, true)
221}
222
223// PadBoth pads both sides of a string if size of string is less then indicated pad length
224func PadBoth(str string, padStr string, padLen int) string {
225return buildPadStr(str, padStr, padLen, true, true)
226}
227
228// PadString either left, right or both sides.
229// Note that padding string can be unicode and more then one character
230func buildPadStr(str string, padStr string, padLen int, padLeft bool, padRight bool) string {
231
232// When padded length is less then the current string size
233if padLen < utf8.RuneCountInString(str) {
234return str
235}
236
237padLen -= utf8.RuneCountInString(str)
238
239targetLen := padLen
240
241targetLenLeft := targetLen
242targetLenRight := targetLen
243if padLeft && padRight {
244targetLenLeft = padLen / 2
245targetLenRight = padLen - targetLenLeft
246}
247
248strToRepeatLen := utf8.RuneCountInString(padStr)
249
250repeatTimes := int(math.Ceil(float64(targetLen) / float64(strToRepeatLen)))
251repeatedString := strings.Repeat(padStr, repeatTimes)
252
253leftSide := ""
254if padLeft {
255leftSide = repeatedString[0:targetLenLeft]
256}
257
258rightSide := ""
259if padRight {
260rightSide = repeatedString[0:targetLenRight]
261}
262
263return leftSide + str + rightSide
264}
265
266// TruncatingErrorf removes extra args from fmt.Errorf if not formatted in the str object
267func TruncatingErrorf(str string, args ...interface{}) error {
268n := strings.Count(str, "%s")
269return fmt.Errorf(str, args[:n]...)
270}
271