podman

Форк
0
394 строки · 9.1 Кб
1
// Copyright 2015 go-swagger maintainers
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
//
7
//    http://www.apache.org/licenses/LICENSE-2.0
8
//
9
// Unless required by applicable law or agreed to in writing, software
10
// distributed under the License is distributed on an "AS IS" BASIS,
11
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12
// See the License for the specific language governing permissions and
13
// limitations under the License.
14

15
package swag
16

17
import (
18
	"reflect"
19
	"strings"
20
	"unicode"
21
)
22

23
// commonInitialisms are common acronyms that are kept as whole uppercased words.
24
var commonInitialisms *indexOfInitialisms
25

26
// initialisms is a slice of sorted initialisms
27
var initialisms []string
28

29
var isInitialism func(string) bool
30

31
// GoNamePrefixFunc sets an optional rule to prefix go names
32
// which do not start with a letter.
33
//
34
// e.g. to help convert "123" into "{prefix}123"
35
//
36
// The default is to prefix with "X"
37
var GoNamePrefixFunc func(string) string
38

39
func init() {
40
	// Taken from https://github.com/golang/lint/blob/3390df4df2787994aea98de825b964ac7944b817/lint.go#L732-L769
41
	var configuredInitialisms = map[string]bool{
42
		"ACL":   true,
43
		"API":   true,
44
		"ASCII": true,
45
		"CPU":   true,
46
		"CSS":   true,
47
		"DNS":   true,
48
		"EOF":   true,
49
		"GUID":  true,
50
		"HTML":  true,
51
		"HTTPS": true,
52
		"HTTP":  true,
53
		"ID":    true,
54
		"IP":    true,
55
		"IPv4":  true,
56
		"IPv6":  true,
57
		"JSON":  true,
58
		"LHS":   true,
59
		"OAI":   true,
60
		"QPS":   true,
61
		"RAM":   true,
62
		"RHS":   true,
63
		"RPC":   true,
64
		"SLA":   true,
65
		"SMTP":  true,
66
		"SQL":   true,
67
		"SSH":   true,
68
		"TCP":   true,
69
		"TLS":   true,
70
		"TTL":   true,
71
		"UDP":   true,
72
		"UI":    true,
73
		"UID":   true,
74
		"UUID":  true,
75
		"URI":   true,
76
		"URL":   true,
77
		"UTF8":  true,
78
		"VM":    true,
79
		"XML":   true,
80
		"XMPP":  true,
81
		"XSRF":  true,
82
		"XSS":   true,
83
	}
84

85
	// a thread-safe index of initialisms
86
	commonInitialisms = newIndexOfInitialisms().load(configuredInitialisms)
87
	initialisms = commonInitialisms.sorted()
88

89
	// a test function
90
	isInitialism = commonInitialisms.isInitialism
91
}
92

93
const (
94
	// collectionFormatComma = "csv"
95
	collectionFormatSpace = "ssv"
96
	collectionFormatTab   = "tsv"
97
	collectionFormatPipe  = "pipes"
98
	collectionFormatMulti = "multi"
99
)
100

101
// JoinByFormat joins a string array by a known format (e.g. swagger's collectionFormat attribute):
102
//
103
//	ssv: space separated value
104
//	tsv: tab separated value
105
//	pipes: pipe (|) separated value
106
//	csv: comma separated value (default)
107
func JoinByFormat(data []string, format string) []string {
108
	if len(data) == 0 {
109
		return data
110
	}
111
	var sep string
112
	switch format {
113
	case collectionFormatSpace:
114
		sep = " "
115
	case collectionFormatTab:
116
		sep = "\t"
117
	case collectionFormatPipe:
118
		sep = "|"
119
	case collectionFormatMulti:
120
		return data
121
	default:
122
		sep = ","
123
	}
124
	return []string{strings.Join(data, sep)}
125
}
126

127
// SplitByFormat splits a string by a known format:
128
//
129
//	ssv: space separated value
130
//	tsv: tab separated value
131
//	pipes: pipe (|) separated value
132
//	csv: comma separated value (default)
133
func SplitByFormat(data, format string) []string {
134
	if data == "" {
135
		return nil
136
	}
137
	var sep string
138
	switch format {
139
	case collectionFormatSpace:
140
		sep = " "
141
	case collectionFormatTab:
142
		sep = "\t"
143
	case collectionFormatPipe:
144
		sep = "|"
145
	case collectionFormatMulti:
146
		return nil
147
	default:
148
		sep = ","
149
	}
150
	var result []string
151
	for _, s := range strings.Split(data, sep) {
152
		if ts := strings.TrimSpace(s); ts != "" {
153
			result = append(result, ts)
154
		}
155
	}
156
	return result
157
}
158

159
type byInitialism []string
160

161
func (s byInitialism) Len() int {
162
	return len(s)
163
}
164
func (s byInitialism) Swap(i, j int) {
165
	s[i], s[j] = s[j], s[i]
166
}
167
func (s byInitialism) Less(i, j int) bool {
168
	if len(s[i]) != len(s[j]) {
169
		return len(s[i]) < len(s[j])
170
	}
171

172
	return strings.Compare(s[i], s[j]) > 0
173
}
174

175
// Removes leading whitespaces
176
func trim(str string) string {
177
	return strings.Trim(str, " ")
178
}
179

180
// Shortcut to strings.ToUpper()
181
func upper(str string) string {
182
	return strings.ToUpper(trim(str))
183
}
184

185
// Shortcut to strings.ToLower()
186
func lower(str string) string {
187
	return strings.ToLower(trim(str))
188
}
189

190
// Camelize an uppercased word
191
func Camelize(word string) (camelized string) {
192
	for pos, ru := range []rune(word) {
193
		if pos > 0 {
194
			camelized += string(unicode.ToLower(ru))
195
		} else {
196
			camelized += string(unicode.ToUpper(ru))
197
		}
198
	}
199
	return
200
}
201

202
// ToFileName lowercases and underscores a go type name
203
func ToFileName(name string) string {
204
	in := split(name)
205
	out := make([]string, 0, len(in))
206

207
	for _, w := range in {
208
		out = append(out, lower(w))
209
	}
210

211
	return strings.Join(out, "_")
212
}
213

214
// ToCommandName lowercases and underscores a go type name
215
func ToCommandName(name string) string {
216
	in := split(name)
217
	out := make([]string, 0, len(in))
218

219
	for _, w := range in {
220
		out = append(out, lower(w))
221
	}
222
	return strings.Join(out, "-")
223
}
224

225
// ToHumanNameLower represents a code name as a human series of words
226
func ToHumanNameLower(name string) string {
227
	in := newSplitter(withPostSplitInitialismCheck).split(name)
228
	out := make([]string, 0, len(in))
229

230
	for _, w := range in {
231
		if !w.IsInitialism() {
232
			out = append(out, lower(w.GetOriginal()))
233
		} else {
234
			out = append(out, w.GetOriginal())
235
		}
236
	}
237

238
	return strings.Join(out, " ")
239
}
240

241
// ToHumanNameTitle represents a code name as a human series of words with the first letters titleized
242
func ToHumanNameTitle(name string) string {
243
	in := newSplitter(withPostSplitInitialismCheck).split(name)
244

245
	out := make([]string, 0, len(in))
246
	for _, w := range in {
247
		original := w.GetOriginal()
248
		if !w.IsInitialism() {
249
			out = append(out, Camelize(original))
250
		} else {
251
			out = append(out, original)
252
		}
253
	}
254
	return strings.Join(out, " ")
255
}
256

257
// ToJSONName camelcases a name which can be underscored or pascal cased
258
func ToJSONName(name string) string {
259
	in := split(name)
260
	out := make([]string, 0, len(in))
261

262
	for i, w := range in {
263
		if i == 0 {
264
			out = append(out, lower(w))
265
			continue
266
		}
267
		out = append(out, Camelize(w))
268
	}
269
	return strings.Join(out, "")
270
}
271

272
// ToVarName camelcases a name which can be underscored or pascal cased
273
func ToVarName(name string) string {
274
	res := ToGoName(name)
275
	if isInitialism(res) {
276
		return lower(res)
277
	}
278
	if len(res) <= 1 {
279
		return lower(res)
280
	}
281
	return lower(res[:1]) + res[1:]
282
}
283

284
// ToGoName translates a swagger name which can be underscored or camel cased to a name that golint likes
285
func ToGoName(name string) string {
286
	lexems := newSplitter(withPostSplitInitialismCheck).split(name)
287

288
	result := ""
289
	for _, lexem := range lexems {
290
		goName := lexem.GetUnsafeGoName()
291

292
		// to support old behavior
293
		if lexem.IsInitialism() {
294
			goName = upper(goName)
295
		}
296
		result += goName
297
	}
298

299
	if len(result) > 0 {
300
		// Only prefix with X when the first character isn't an ascii letter
301
		first := []rune(result)[0]
302
		if !unicode.IsLetter(first) || (first > unicode.MaxASCII && !unicode.IsUpper(first)) {
303
			if GoNamePrefixFunc == nil {
304
				return "X" + result
305
			}
306
			result = GoNamePrefixFunc(name) + result
307
		}
308
		first = []rune(result)[0]
309
		if unicode.IsLetter(first) && !unicode.IsUpper(first) {
310
			result = string(append([]rune{unicode.ToUpper(first)}, []rune(result)[1:]...))
311
		}
312
	}
313

314
	return result
315
}
316

317
// ContainsStrings searches a slice of strings for a case-sensitive match
318
func ContainsStrings(coll []string, item string) bool {
319
	for _, a := range coll {
320
		if a == item {
321
			return true
322
		}
323
	}
324
	return false
325
}
326

327
// ContainsStringsCI searches a slice of strings for a case-insensitive match
328
func ContainsStringsCI(coll []string, item string) bool {
329
	for _, a := range coll {
330
		if strings.EqualFold(a, item) {
331
			return true
332
		}
333
	}
334
	return false
335
}
336

337
type zeroable interface {
338
	IsZero() bool
339
}
340

341
// IsZero returns true when the value passed into the function is a zero value.
342
// This allows for safer checking of interface values.
343
func IsZero(data interface{}) bool {
344
	v := reflect.ValueOf(data)
345
	// check for nil data
346
	switch v.Kind() {
347
	case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
348
		if v.IsNil() {
349
			return true
350
		}
351
	}
352

353
	// check for things that have an IsZero method instead
354
	if vv, ok := data.(zeroable); ok {
355
		return vv.IsZero()
356
	}
357

358
	// continue with slightly more complex reflection
359
	switch v.Kind() {
360
	case reflect.String:
361
		return v.Len() == 0
362
	case reflect.Bool:
363
		return !v.Bool()
364
	case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
365
		return v.Int() == 0
366
	case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
367
		return v.Uint() == 0
368
	case reflect.Float32, reflect.Float64:
369
		return v.Float() == 0
370
	case reflect.Struct, reflect.Array:
371
		return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface())
372
	case reflect.Invalid:
373
		return true
374
	default:
375
		return false
376
	}
377
}
378

379
// AddInitialisms add additional initialisms
380
func AddInitialisms(words ...string) {
381
	for _, word := range words {
382
		// commonInitialisms[upper(word)] = true
383
		commonInitialisms.add(upper(word))
384
	}
385
	// sort again
386
	initialisms = commonInitialisms.sorted()
387
}
388

389
// CommandLineOptionsGroup represents a group of user-defined command line options
390
type CommandLineOptionsGroup struct {
391
	ShortDescription string
392
	LongDescription  string
393
	Options          interface{}
394
}
395

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.