Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.

69 рядки
2.2 KiB

  1. /*
  2. * The MIT License (MIT)
  3. *
  4. * Copyright (c) 2015 Ian Coleman
  5. * Copyright (c) 2018 Ma_124, <github.com/Ma124>
  6. *
  7. * Permission is hereby granted, free of charge, to any person obtaining a copy
  8. * of this software and associated documentation files (the "Software"), to deal
  9. * in the Software without restriction, including without limitation the rights
  10. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  11. * copies of the Software, and to permit persons to whom the Software is
  12. * furnished to do so, Subject to the following conditions:
  13. *
  14. * The above copyright notice and this permission notice shall be included in all
  15. * copies or Substantial portions of the Software.
  16. *
  17. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  18. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  19. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  20. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  21. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  22. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
  23. * SOFTWARE.
  24. */
  25. // Package strcase converts strings to snake_case or CamelCase
  26. package strcase
  27. import (
  28. "strings"
  29. )
  30. // Converts a string to snake_case
  31. func ToSnake(s string) string {
  32. return ToDelimited(s, '_')
  33. }
  34. func ToDelimited(s string, del uint8) string {
  35. s = addWordBoundariesToNumbers(s)
  36. s = strings.Trim(s, " ")
  37. n := ""
  38. for i, v := range s {
  39. // treat acronyms as words, eg for JSONData -> JSON is a whole word
  40. nextCaseIsChanged := false
  41. if i+1 < len(s) {
  42. next := s[i+1]
  43. if (v >= 'A' && v <= 'Z' && next >= 'a' && next <= 'z') || (v >= 'a' && v <= 'z' && next >= 'A' && next <= 'Z') {
  44. nextCaseIsChanged = true
  45. }
  46. }
  47. if i > 0 && n[len(n)-1] != del && nextCaseIsChanged {
  48. // add underscore if next letter case type is changed
  49. if v >= 'A' && v <= 'Z' {
  50. n += string(del) + string(v)
  51. } else if v >= 'a' && v <= 'z' {
  52. n += string(v) + string(del)
  53. }
  54. } else if v == ' ' || v == '_' || v == '-' {
  55. // replace spaces/underscores with delimiters
  56. n += string(del)
  57. } else {
  58. n = n + string(v)
  59. }
  60. }
  61. n = strings.ToLower(n)
  62. return n
  63. }