util.go 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406
  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. package swag
  15. import (
  16. "math"
  17. "reflect"
  18. "regexp"
  19. "strings"
  20. "sync"
  21. "unicode"
  22. )
  23. // commonInitialisms are common acronyms that are kept as whole uppercased words.
  24. var commonInitialisms *indexOfInitialisms
  25. // initialisms is a slice of sorted initialisms
  26. var initialisms []string
  27. var once sync.Once
  28. var isInitialism func(string) bool
  29. func init() {
  30. // Taken from https://github.com/golang/lint/blob/3390df4df2787994aea98de825b964ac7944b817/lint.go#L732-L769
  31. var configuredInitialisms = map[string]bool{
  32. "ACL": true,
  33. "API": true,
  34. "ASCII": true,
  35. "CPU": true,
  36. "CSS": true,
  37. "DNS": true,
  38. "EOF": true,
  39. "GUID": true,
  40. "HTML": true,
  41. "HTTPS": true,
  42. "HTTP": true,
  43. "ID": true,
  44. "IP": true,
  45. "JSON": true,
  46. "LHS": true,
  47. "OAI": true,
  48. "QPS": true,
  49. "RAM": true,
  50. "RHS": true,
  51. "RPC": true,
  52. "SLA": true,
  53. "SMTP": true,
  54. "SQL": true,
  55. "SSH": true,
  56. "TCP": true,
  57. "TLS": true,
  58. "TTL": true,
  59. "UDP": true,
  60. "UI": true,
  61. "UID": true,
  62. "UUID": true,
  63. "URI": true,
  64. "URL": true,
  65. "UTF8": true,
  66. "VM": true,
  67. "XML": true,
  68. "XMPP": true,
  69. "XSRF": true,
  70. "XSS": true,
  71. }
  72. // a thread-safe index of initialisms
  73. commonInitialisms = newIndexOfInitialisms().load(configuredInitialisms)
  74. // a test function
  75. isInitialism = commonInitialisms.isInitialism
  76. }
  77. func ensureSorted() {
  78. initialisms = commonInitialisms.sorted()
  79. }
  80. const (
  81. //collectionFormatComma = "csv"
  82. collectionFormatSpace = "ssv"
  83. collectionFormatTab = "tsv"
  84. collectionFormatPipe = "pipes"
  85. collectionFormatMulti = "multi"
  86. )
  87. // JoinByFormat joins a string array by a known format (e.g. swagger's collectionFormat attribute):
  88. // ssv: space separated value
  89. // tsv: tab separated value
  90. // pipes: pipe (|) separated value
  91. // csv: comma separated value (default)
  92. func JoinByFormat(data []string, format string) []string {
  93. if len(data) == 0 {
  94. return data
  95. }
  96. var sep string
  97. switch format {
  98. case collectionFormatSpace:
  99. sep = " "
  100. case collectionFormatTab:
  101. sep = "\t"
  102. case collectionFormatPipe:
  103. sep = "|"
  104. case collectionFormatMulti:
  105. return data
  106. default:
  107. sep = ","
  108. }
  109. return []string{strings.Join(data, sep)}
  110. }
  111. // SplitByFormat splits a string by a known format:
  112. // ssv: space separated value
  113. // tsv: tab separated value
  114. // pipes: pipe (|) separated value
  115. // csv: comma separated value (default)
  116. //
  117. func SplitByFormat(data, format string) []string {
  118. if data == "" {
  119. return nil
  120. }
  121. var sep string
  122. switch format {
  123. case collectionFormatSpace:
  124. sep = " "
  125. case collectionFormatTab:
  126. sep = "\t"
  127. case collectionFormatPipe:
  128. sep = "|"
  129. case collectionFormatMulti:
  130. return nil
  131. default:
  132. sep = ","
  133. }
  134. var result []string
  135. for _, s := range strings.Split(data, sep) {
  136. if ts := strings.TrimSpace(s); ts != "" {
  137. result = append(result, ts)
  138. }
  139. }
  140. return result
  141. }
  142. type byLength []string
  143. func (s byLength) Len() int {
  144. return len(s)
  145. }
  146. func (s byLength) Swap(i, j int) {
  147. s[i], s[j] = s[j], s[i]
  148. }
  149. func (s byLength) Less(i, j int) bool {
  150. return len(s[i]) < len(s[j])
  151. }
  152. // Prepares strings by splitting by caps, spaces, dashes, and underscore
  153. func split(str string) []string {
  154. repl := strings.NewReplacer(
  155. "@", "At ",
  156. "&", "And ",
  157. "|", "Pipe ",
  158. "$", "Dollar ",
  159. "!", "Bang ",
  160. "-", " ",
  161. "_", " ",
  162. )
  163. rex1 := regexp.MustCompile(`(\p{Lu})`)
  164. rex2 := regexp.MustCompile(`(\pL|\pM|\pN|\p{Pc})+`)
  165. str = trim(str)
  166. // Convert dash and underscore to spaces
  167. str = repl.Replace(str)
  168. // Split when uppercase is found (needed for Snake)
  169. str = rex1.ReplaceAllString(str, " $1")
  170. // check if consecutive single char things make up an initialism
  171. once.Do(ensureSorted)
  172. for _, k := range initialisms {
  173. str = strings.Replace(str, rex1.ReplaceAllString(k, " $1"), " "+k, -1)
  174. }
  175. // Get the final list of words
  176. //words = rex2.FindAllString(str, -1)
  177. return rex2.FindAllString(str, -1)
  178. }
  179. // Removes leading whitespaces
  180. func trim(str string) string {
  181. return strings.Trim(str, " ")
  182. }
  183. // Shortcut to strings.ToUpper()
  184. func upper(str string) string {
  185. return strings.ToUpper(trim(str))
  186. }
  187. // Shortcut to strings.ToLower()
  188. func lower(str string) string {
  189. return strings.ToLower(trim(str))
  190. }
  191. // Camelize an uppercased word
  192. func Camelize(word string) (camelized string) {
  193. for pos, ru := range word {
  194. if pos > 0 {
  195. camelized += string(unicode.ToLower(ru))
  196. } else {
  197. camelized += string(unicode.ToUpper(ru))
  198. }
  199. }
  200. return
  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. for _, w := range in {
  207. out = append(out, lower(w))
  208. }
  209. return strings.Join(out, "_")
  210. }
  211. // ToCommandName lowercases and underscores a go type name
  212. func ToCommandName(name string) string {
  213. in := split(name)
  214. out := make([]string, 0, len(in))
  215. for _, w := range in {
  216. out = append(out, lower(w))
  217. }
  218. return strings.Join(out, "-")
  219. }
  220. // ToHumanNameLower represents a code name as a human series of words
  221. func ToHumanNameLower(name string) string {
  222. in := split(name)
  223. out := make([]string, 0, len(in))
  224. for _, w := range in {
  225. if !isInitialism(upper(w)) {
  226. out = append(out, lower(w))
  227. } else {
  228. out = append(out, w)
  229. }
  230. }
  231. return strings.Join(out, " ")
  232. }
  233. // ToHumanNameTitle represents a code name as a human series of words with the first letters titleized
  234. func ToHumanNameTitle(name string) string {
  235. in := split(name)
  236. out := make([]string, 0, len(in))
  237. for _, w := range in {
  238. uw := upper(w)
  239. if !isInitialism(uw) {
  240. out = append(out, upper(w[:1])+lower(w[1:]))
  241. } else {
  242. out = append(out, w)
  243. }
  244. }
  245. return strings.Join(out, " ")
  246. }
  247. // ToJSONName camelcases a name which can be underscored or pascal cased
  248. func ToJSONName(name string) string {
  249. in := split(name)
  250. out := make([]string, 0, len(in))
  251. for i, w := range in {
  252. if i == 0 {
  253. out = append(out, lower(w))
  254. continue
  255. }
  256. out = append(out, upper(w[:1])+lower(w[1:]))
  257. }
  258. return strings.Join(out, "")
  259. }
  260. // ToVarName camelcases a name which can be underscored or pascal cased
  261. func ToVarName(name string) string {
  262. res := ToGoName(name)
  263. if isInitialism(res) {
  264. return lower(res)
  265. }
  266. if len(res) <= 1 {
  267. return lower(res)
  268. }
  269. return lower(res[:1]) + res[1:]
  270. }
  271. // ToGoName translates a swagger name which can be underscored or camel cased to a name that golint likes
  272. func ToGoName(name string) string {
  273. in := split(name)
  274. out := make([]string, 0, len(in))
  275. for _, w := range in {
  276. uw := upper(w)
  277. mod := int(math.Min(float64(len(uw)), 2))
  278. if !isInitialism(uw) && !isInitialism(uw[:len(uw)-mod]) {
  279. uw = upper(w[:1]) + lower(w[1:])
  280. }
  281. out = append(out, uw)
  282. }
  283. result := strings.Join(out, "")
  284. if len(result) > 0 {
  285. ud := upper(result[:1])
  286. ru := []rune(ud)
  287. if unicode.IsUpper(ru[0]) {
  288. result = ud + result[1:]
  289. } else {
  290. result = "X" + ud + result[1:]
  291. }
  292. }
  293. return result
  294. }
  295. // ContainsStrings searches a slice of strings for a case-sensitive match
  296. func ContainsStrings(coll []string, item string) bool {
  297. for _, a := range coll {
  298. if a == item {
  299. return true
  300. }
  301. }
  302. return false
  303. }
  304. // ContainsStringsCI searches a slice of strings for a case-insensitive match
  305. func ContainsStringsCI(coll []string, item string) bool {
  306. for _, a := range coll {
  307. if strings.EqualFold(a, item) {
  308. return true
  309. }
  310. }
  311. return false
  312. }
  313. type zeroable interface {
  314. IsZero() bool
  315. }
  316. // IsZero returns true when the value passed into the function is a zero value.
  317. // This allows for safer checking of interface values.
  318. func IsZero(data interface{}) bool {
  319. // check for things that have an IsZero method instead
  320. if vv, ok := data.(zeroable); ok {
  321. return vv.IsZero()
  322. }
  323. // continue with slightly more complex reflection
  324. v := reflect.ValueOf(data)
  325. switch v.Kind() {
  326. case reflect.String:
  327. return v.Len() == 0
  328. case reflect.Bool:
  329. return !v.Bool()
  330. case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
  331. return v.Int() == 0
  332. case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Uintptr:
  333. return v.Uint() == 0
  334. case reflect.Float32, reflect.Float64:
  335. return v.Float() == 0
  336. case reflect.Interface, reflect.Map, reflect.Ptr, reflect.Slice:
  337. return v.IsNil()
  338. case reflect.Struct, reflect.Array:
  339. return reflect.DeepEqual(data, reflect.Zero(v.Type()).Interface())
  340. case reflect.Invalid:
  341. return true
  342. }
  343. return false
  344. }
  345. // AddInitialisms add additional initialisms
  346. func AddInitialisms(words ...string) {
  347. for _, word := range words {
  348. //commonInitialisms[upper(word)] = true
  349. commonInitialisms.add(upper(word))
  350. }
  351. // sort again
  352. initialisms = commonInitialisms.sorted()
  353. }
  354. // CommandLineOptionsGroup represents a group of user-defined command line options
  355. type CommandLineOptionsGroup struct {
  356. ShortDescription string
  357. LongDescription string
  358. Options interface{}
  359. }