util.go 9.3 KB

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