shell dot on steroids https://pagure.io/shellfu

coerce.sh 2.4KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/bin/sh
  2. #
  3. # Data coercion helpers
  4. #
  5. # This module provides several simple functions to help transform
  6. # data to fit certain constraints.
  7. #
  8. #
  9. # Replacement character
  10. #
  11. COERCE__REPCHAR=${COERCE__REPCHAR:-�}
  12. coerce__nocolor() {
  13. #
  14. # Remove ANSI color codes
  15. #
  16. if $__COERCE__LEGACY; then
  17. sed 's/\x1b\[[0-9;]*m//g'
  18. else
  19. perl -CS -Mutf8 -MTerm::ANSIColor=colorstrip -ne 'print colorstrip $_;'
  20. fi
  21. }
  22. coerce__noctl() {
  23. #
  24. # Replace non-printable characters with $COERCE__REPCHAR
  25. #
  26. perl -CS -Mutf8 -pe "s|[^[:graph:] \t\n]|$COERCE__REPCHAR|g"
  27. }
  28. coerce__nofdraw() {
  29. #
  30. # Replace frame-drawing characters with ASCII
  31. #
  32. # Replace frame-drawing characters according
  33. # to following mapping:
  34. #
  35. # ┌ ┬ ┐ └ ┴ ┘ ├ ┤ │ ┼ ─
  36. #
  37. # ' ' ' . . . | | | | -
  38. #
  39. # This converts frame-drawing to ASCII, making it
  40. # safer when fonts on terminals are not rendering
  41. # properly.
  42. #
  43. perl -CS -Mutf8 -pe "
  44. tr{┌┬┐}{.};
  45. tr{└┴┘}{'};
  46. tr{├┼┤│}{|};
  47. tr{─}{-};
  48. "
  49. }
  50. coerce__for_yaml() {
  51. #
  52. # Replace yaml-invalid characters
  53. #
  54. # Yaml won't allow all characters:
  55. #
  56. # > [...] The allowed character range explicitly excludes the C0 control
  57. # > block #x0-#x1F (except for TAB #x9, LF #xA, and CR #xD which are
  58. # > allowed), DEL #x7F, the C1 control block #x80-#x9F (except for NEL
  59. # > #x85 which is allowed), the surrogate block #xD800-#xDFFF, #xFFFE,
  60. # > and #xFFFF.
  61. #
  62. # so take stdin and replace all unacceptable characters with '�'.
  63. #
  64. perl -CS -Mutf8 -pe "tr/$(__coerce__for_yaml_bad)/$COERCE__REPCHAR/"
  65. }
  66. #
  67. # Legacy mode
  68. #
  69. # If 'true', avoids using Term::ANSIColor in favor of a local hacky
  70. # sed expression yanked from stackoverflow. Use if Term::ANSIColor
  71. # is not available (as is case of eg. RHEL-6).
  72. #
  73. __COERCE__LEGACY=${__COERCE__LEGACY:-false}
  74. __coerce__for_yaml_bad() {
  75. #
  76. # Print all YAML-bad chars
  77. #
  78. printf '\N{U+0}-\N{U+8}\N{U+B}\N{U+C}\N{U+E}-\N{U+1F}' # C0 with some gaps
  79. printf '\N{U+7F}' # DEL alone
  80. printf '\N{U+80}-\N{U+84}\N{U+86}-\N{U+9F}' # C1 with NEL gap
  81. # printf -n '\N{U+D800}-\N{U+DFFF}' # surrogates
  82. # printf -n '\N{U+FFFE}-\N{U+FFFF}' # 0xFFFE and 0xFFFF
  83. #FIXME: for some reasons perl complains about these ^^
  84. }