cat-recursively.sh 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. #!/usr/bin/env bash
  2. set -euo pipefail # bash strict mode
  3. display_help() {
  4. cat <<EOF
  5. Usage: ${0##*/} [OPTIONS] [FILES...]
  6. Process the given files and directories.
  7. Options:
  8. -j Format output for JIRA
  9. -m Format output for Markdown
  10. -h Display this help message and exit
  11. Arguments:
  12. FILES... List of files and directories to process. Directories will be searched for text files, and individual files will be processed as specified.
  13. Examples:
  14. ${0##*/} -j file1.txt file2.txt
  15. ${0##*/} -m dir1 dir2 file3.txt
  16. EOF
  17. exit 2
  18. }
  19. markdown_format(){
  20. local file="$1"
  21. cat <<EOF
  22. ==== ${file} ====
  23. \`\`\`
  24. $(< "$file")
  25. \`\`\`
  26. EOF
  27. }
  28. jira_format(){
  29. local file="$1"
  30. cat <<EOF
  31. ==== ${file} ====
  32. {code:java}
  33. $(< "$file")
  34. {code}
  35. EOF
  36. }
  37. 4chan_format(){
  38. local file="$1"
  39. cat <<EOF
  40. ==== ${file} ====
  41. [code]
  42. $(< "$file")
  43. [/code]
  44. EOF
  45. }
  46. format(){
  47. local file="$1"
  48. case "${format_option:-}" in
  49. j) jira_format "$file" ;;
  50. 4) 4chan_format "$file" ;;
  51. m|*) markdown_format "$file" ;;
  52. esac
  53. }
  54. while getopts 'jm4h' opt; do
  55. case "$opt" in
  56. j|m|4) format_option="$opt" ;;
  57. h|\?|:|*) display_help ;;
  58. esac
  59. done
  60. shift $((OPTIND-1))
  61. for thing in "$@"; do
  62. if [[ -d $thing ]]; then
  63. dirs+=("$thing")
  64. elif [[ -f $thing ]]; then
  65. files+=("$thing")
  66. else
  67. echo "I don't know what is ${thing}"
  68. fi
  69. done
  70. [[ ${dirs:-} ]] && mapfile -t ALL_FILES < <(find "${dirs[@]}" -type f -not \( -path '*/.git/*' -o -path '*/www/*' \) | sort)
  71. [[ ${files:-} ]] && ALL_FILES+=("${files[@]}")
  72. for file in "${ALL_FILES[@]}"; do
  73. if [[ $(file -b --mime-type "$file") =~ 'text' ]]; then
  74. format "$file"
  75. fi
  76. done