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

coerce.sh 2.1KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  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. perl -CS -Mutf8 -MTerm::ANSIColor=colorstrip -ne 'print colorstrip $_;'
  17. }
  18. coerce__noctl() {
  19. #
  20. # Remove non-printable characters
  21. #
  22. perl -CS -Mutf8 -pe 'tr|[:graph:]\n\t ||c;'
  23. }
  24. coerce__nofdraw() {
  25. #
  26. # Replace frame-drawing characters with ASCII
  27. #
  28. # Replace frame-drawing characters according
  29. # to following mapping:
  30. #
  31. # ┌ ┬ ┐ └ ┴ ┘ ├ ┤ │ ┼ ─
  32. #
  33. # ' ' ' . . . | | | | -
  34. #
  35. # This converts frame-drawing to ASCII, making it
  36. # safer when fonts on terminals are not rendering
  37. # properly.
  38. #
  39. perl -CS -Mutf8 -pe "
  40. tr{┌┬┐}{.};
  41. tr{└┴┘}{'};
  42. tr{├┼┤│}{|};
  43. tr{─}{-};
  44. "
  45. }
  46. coerce__for_yaml() {
  47. #
  48. # Replace yaml-invalid characters
  49. #
  50. # Yaml won't allow all characters:
  51. #
  52. # > [...] The allowed character range explicitly excludes the C0 control
  53. # > block #x0-#x1F (except for TAB #x9, LF #xA, and CR #xD which are
  54. # > allowed), DEL #x7F, the C1 control block #x80-#x9F (except for NEL
  55. # > #x85 which is allowed), the surrogate block #xD800-#xDFFF, #xFFFE,
  56. # > and #xFFFF.
  57. #
  58. # so take stdin and replace all unacceptable characters with '�'.
  59. #
  60. perl -CS -Mutf8 -pe "tr/$(__coerce__for_yaml_bad)/$COERCE__REPCHAR/"
  61. }
  62. __coerce__for_yaml_bad() {
  63. #
  64. # Print all YAML-bad chars
  65. #
  66. printf '\N{U+0}-\N{U+8}\N{U+B}\N{U+C}\N{U+E}-\N{U+1F}' # C0 with some gaps
  67. printf '\N{U+7F}' # DEL alone
  68. printf '\N{U+80}-\N{U+84}\N{U+86}-\N{U+9F}' # C1 with NEL gap
  69. # printf -n '\N{U+D800}-\N{U+DFFF}' # surrogates
  70. # printf -n '\N{U+FFFE}-\N{U+FFFF}' # 0xFFFE and 0xFFFF
  71. #FIXME: for some reasons perl complains about these ^^
  72. }