addCodespellIgnores.sh 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. #!/bin/bash
  2. # Copyright (C) 2024 MDW <mdeweerd@users.noreply.github.com>
  3. #
  4. # Script to add codespell exceptions to the ignores lines file.
  5. #
  6. # The file is named '...-lines-ignore' to make TAB expansion on the cli easier.
  7. #
  8. # The line in the ignore file must match the line in the source
  9. # exactly.
  10. #
  11. # To clean up or create the ignored lines file, just do
  12. # ```shell
  13. # echo > dev/tools/codespell/codespell-lines-ignore.txt
  14. # ```
  15. # and then execute this script.
  16. #
  17. # author: https://github.com/mdeweerd
  18. #
  19. # :warning:
  20. #
  21. # This script only works properly if codespell is installed for your CLI.
  22. # As the configuration is in pyproject.toml, you also need tomli.
  23. #
  24. # ```shell
  25. # python -m pip install codespell tomli
  26. # # or
  27. # pip install codespell tomli
  28. # ```
  29. codespell_ignore_file=dev/tools/codespell/codespell-lines-ignore.txt
  30. if [ -z "${0##*.sh}" ] ; then
  31. # Suppose running from inside script
  32. # Get real path
  33. script=$(realpath "$(test -L "$0" && readlink "$0" || echo "$0")")
  34. PROJECT_ROOT=$(realpath "${script}")
  35. while [ "${PROJECT_ROOT}" != "/" ] ; do
  36. [ -r "${PROJECT_ROOT}/${codespell_ignore_file}" ] && break
  37. PROJECT_ROOT=$(dirname "${PROJECT_ROOT}")
  38. done
  39. if [ "${PROJECT_ROOT}" == "/" ] ; then
  40. echo "Project root not found from '${script}'"
  41. exit 1
  42. fi
  43. codespell_ignore_file=${PROJECT_ROOT}/${codespell_ignore_file}
  44. fi
  45. # Make sure we are at the root of the project
  46. [ -r "${codespell_ignore_file}" ] || { echo "${codespell_ignore_file} not found" ; exit 1 ; }
  47. # Then:
  48. # - Run codespell;
  49. # - Identify files that have fixes;
  50. # - Limit to files under git control;
  51. # - Run codespell on selected files;
  52. # - For each line, create a grep command to find the lines;
  53. # - Execute that command by evaluation
  54. codespell . \
  55. | sed -n -E 's@^([^:]+):.*@\1@p' \
  56. | xargs -r git ls-files -- \
  57. | xargs -r codespell -- \
  58. | sed -n -E 's@^([^:]+):[[:digit:]]+:[[:space:]](\S+)[[:space:]].*@grep -P '\''\\b\2\\b'\'' -- "\1" >> '"${codespell_ignore_file}"'@p' \
  59. | while read -r line ; do eval "$line" ; done
  60. # Finally, sort and remove duplicates to make merges easier.
  61. sort -u -o "${codespell_ignore_file}"{,}