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

coerce.sh 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. # Keep only characters that have grapgical representation ([:graph:] POSIX
  27. # class), newline, tab and space. Replace rest with $COERCE__REPCHAR.
  28. #
  29. perl -CS -Mutf8 -pe "s|[^[:graph:] \t\n]|$COERCE__REPCHAR|g"
  30. }
  31. coerce__nofdraw() {
  32. #
  33. # Replace frame-drawing characters with ASCII
  34. #
  35. # Replace frame-drawing characters according
  36. # to following mapping:
  37. #
  38. # ┌ ┬ ┐ └ ┴ ┘ ├ ┤ │ ┼ ─
  39. #
  40. # ' ' ' . . . | | | | -
  41. #
  42. # This converts frame-drawing to ASCII, making it
  43. # safer when fonts on terminals are not rendering
  44. # properly.
  45. #
  46. perl -CS -Mutf8 -pe "
  47. tr{┌┬┐}{.};
  48. tr{└┴┘}{'};
  49. tr{├┼┤│}{|};
  50. tr{─}{-};
  51. "
  52. }
  53. coerce__for_yaml() {
  54. #
  55. # Replace yaml-invalid characters
  56. #
  57. # Yaml won't allow all characters:
  58. #
  59. # > [...] The allowed character range explicitly excludes the C0 control
  60. # > block #x0-#x1F (except for TAB #x9, LF #xA, and CR #xD which are
  61. # > allowed), DEL #x7F, the C1 control block #x80-#x9F (except for NEL
  62. # > #x85 which is allowed), the surrogate block #xD800-#xDFFF, #xFFFE,
  63. # > and #xFFFF.
  64. #
  65. # so take stdin and replace all unacceptable characters with '�'.
  66. #
  67. perl -CS -Mutf8 -pe "tr/$(__coerce__for_yaml_bad)/$COERCE__REPCHAR/"
  68. }
  69. #
  70. # Legacy mode
  71. #
  72. # If 'true', avoids using Term::ANSIColor in favor of a local hacky
  73. # sed expression yanked from stackoverflow. Use if Term::ANSIColor
  74. # is not available (as is case of eg. RHEL-6).
  75. #
  76. __COERCE__LEGACY=${__COERCE__LEGACY:-false}
  77. __coerce__for_yaml_bad() {
  78. #
  79. # Print all YAML-bad chars
  80. #
  81. printf '\N{U+0}-\N{U+8}\N{U+B}\N{U+C}\N{U+E}-\N{U+1F}' # C0 with some gaps
  82. printf '\N{U+7F}' # DEL alone
  83. printf '\N{U+80}-\N{U+84}\N{U+86}-\N{U+9F}' # C1 with NEL gap
  84. # printf -n '\N{U+D800}-\N{U+DFFF}' # surrogates
  85. # printf -n '\N{U+FFFE}-\N{U+FFFF}' # 0xFFFE and 0xFFFF
  86. #FIXME: for some reasons perl complains about these ^^
  87. }